@EnableConfigurationProperties的作用是把springboot配置文件中的值与我们的xxxProperties.java的属性进行绑定,需要配合@ConfigurationProperties使用 首先我想说的是,不使用@EnableConfigurationProperties能否进行属性绑定呢?答案是肯定的!我们只需要给xxxProperties.java加上@Component注解,把它放到容器中,即可实现属性绑定
测试实例如下:
@Component
@Data
@ConfigurationProperties(prefix = "person")
public class PersonProperties {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
application.properties:
person.last-name=宁宁
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=小黄
person.dog.age=5
测试类:
@RestController
//@EnableConfigurationProperties(Person.class)
public class HelloController {
@Autowired
PersonProperties person;
@RequestMapping("/sayHello")
public String sayHello() {
System.out.println(person);
return null;
}
}
测试效果:
我们再来看看@EnableConfigurationProperties的用法,把PersonProperties的@Component注解去掉
//@Component
@Data
@ConfigurationProperties(prefix = "person")
public class PersonProperties {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
再在HelloController上加上@EnableConfigurationProperties注解
@RestController
@EnableConfigurationProperties(PersonProperties.class)
public class HelloController {
@Autowired
PersonProperties person;
@RequestMapping("/sayHello")
public String sayHello() {
System.out.println(person);
return null;
}
}
测试效果和上面一样,就不贴出来了!
从上面的示例中,我们可以看到在属性绑定中@EnableConfigurationProperties和@Component的效果一样,那么为啥springboot还要使用这个注解呢?
答案是:当我们引用第三方jar包时,@Component标注的类是无法注入到spring容器中的,这时我们可以用@EnableConfigurationProperties来代替@Component