关于@ConfigurationProperties

springboot使用@ConfigurationProperties注解,可以对配置文件中的配置绑定到一个类中

比如,我们在配置文件application.yml中写入下列代码

person:
  name: linyongbin
  age: 21
  single: false

然后,创建一个类Person,我只是随便取个名字,你想把这个类叫什么都没关系

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Boolean single;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", single=" + single +
                '}';
    }
#此处省略get和set方法

}
可以注意到我们使用了@ConfigurationProperties注解,并且还有(prefix = "person"),其中prefix 指定了配置文件中的person

就可以将配置文件中的person配置绑定到Person类中,然后使用@Component将类作为spring里面的一个组件,那么它就可以使用相应的功能了

我们编写测试类进行person的输出

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    Person person;

    @Test
    public void contextLoads() {
        System.out.println(person.toString());
      
    }

}

可以看到输出了Person{name='linyongbin', age=21, single=false}

但是我不知道是否能够通过Person类来对配置文件中的值进行改变,我使用person.setage(22)测试了,没有改变,如果你们知道如何改变,可以评论告诉我,谢谢

猜你喜欢

转载自blog.csdn.net/abc_123456___/article/details/90552627
今日推荐