赞
踩
在实体上使用@ConfigurationProperties注解,可以读取配置文件中同类配置信息并封装成对象。和@Bean注解同时使用时可以不用在实体上使用该注解。
满足以下三条可以成功注入:
示例代码:
public class Parent { private String userType; public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } @Override public String toString() { return "Parent [userType=" + userType + "]"; } }
@ConfigurationProperties(prefix = "test") public class Son extends Parent { private String userName; private Integer age; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Son [userName=" + userName + ", age=" + age + ", toString()=" + super.toString() + "]"; } }
配置文件中相关配置:
test.user-name=Qiwan
test.age=18
test.user-type=human
执行单元测试:
@Autowired
private Son son;
@Test
public void test1(){
log.info("SON:{}", son);
}
输出结果: SON:Son [userName=Qiwan, age=18, toString()=Parent [userType=human]]
和@Bean注解同时使用时:
去掉Son类上的@ConfigurationProperties(prefix = “test”)注解,增加SonConfig类。
@Configuration
public class SonConfig {
@Bean
@ConfigurationProperties(prefix = "test")
public Son getSon(){
return new Son();
}
}
执行上述相同单元测试代码,结果同上。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。