具体可以查看这篇:https://www.cnblogs.com/dalianpai/p/11772382.html
原始的
/** * @author WGR * @create 2019/12/6 -- 15:14 */ @Component @ConfigurationProperties("person") public class Person { private String lastName; private Integer age; private Boolean boss; private Map<String, Object> maps; private List<Object> lists; @Override public String toString() { return "Person{" + "lastName='" + lastName + '\'' + ", age=" + age + ", boss=" + boss + ", maps=" + maps + ", lists=" + lists + '}'; } @Override public int hashCode() { return Objects.hash(lastName, age, boss, maps, lists); } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getBoss() { return boss; } public void setBoss(Boolean boss) { this.boss = boss; } public Map<String, Object> getMaps() { return maps; } public void setMaps(Map<String, Object> maps) { this.maps = maps; } public List<Object> getLists() { return lists; } public void setLists(List<Object> lists) { this.lists = lists; } }
@Autowired Person person; @GetMapping("/test") public Person test(){ return person; }
测试结果:
{"lastName":"wgr","age":20,"boss":null,"maps":null,"lists":null}
2.2.1.RELEASE
SpringBoot
2.2.1.RELEASE版本中@SpringBootApplication
注解部分源码如下所示:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { //... }
我们发现在SpringBoot
2.2.1.RELEASE版本的@SpringBootApplication
注解中已经不再默认添加@ConfigurationPropertiesScan
注解的支持了,也就是我们无法通过默认的配置实现扫描@ConfigurationProperties
注解的类,也无法将application.yml/application.properties
文件的配置内容与实体类内的属性进行绑定。
加入@ConfigurationPropertiesScan
@ConfigurationPropertiesScan public class Mongodb2Application { @Autowired(required=false) Person person; @GetMapping("/test") public Person test(){ return person; } }
@ConfigurationProperties( prefix = "person") //@ConstructorBinding //@Component public class Person { private String lastName; private Integer age; public void setLastName(String lastName) { this.lastName = lastName; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Person{" + "lastName='" + lastName + '\'' + ", age=" + age + '}'; } // public Person(String lastName, Integer age) { // this.lastName = lastName; // this.age = age; // } public String getLastName() { return lastName; } public Integer getAge() { return age; } }
可以不要在Person上加@Component注解了。