参考文章springboot(四)——@EnableConfigurationProperties是如何起作用的你知道吗
前言
用springboot开发的过程中,我们会用到@ConfigurationProperties注解,主要是用来把properties或者yml配置文件转化为bean来使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。
如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的,当然在@ConfigurationProperties加入注解的类上加@Component也可以使交于springboot管理
举个栗子
第一步:创建一个类TestConfigurationProperties
@ConfigurationProperties(prefix = "properties")
public class TestConfigurationProperties {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 省略set和get方法
}
第二步:创建TestAutoConfiguration类
@Configuration
@EnableConfigurationProperties(TestConfigurationProperties.class) // 将TestConfigurationProperties放入IOC容器中
@ConditionalOnClass(User.class) // 类路径中有user类时,才会加载这个配置类
@ConditionalOnProperty(prefix = "test", value = "enabled", havingValue = "true") // 配置文件中有test.enable=true的配置,才会加载这个配置类
public class TestAutoConfiguration {
@Autowired
private TestConfigurationProperties testConfigurationProperties;
@Bean
public User user(){
User user = new User();
user.setName(testConfigurationProperties.getName());
return user;
}
}
第三步:配置文件加入属性
properties.name=test
test.enable=true
第四步:跑一下,打印出User这个类
@RestController
@RequestMapping("/api/test")
@Slf4j
public class TestController {
@Autowired
TestConfigurationProperties testConfigurationProperties;
@Autowired
User user;
@RequestMapping(value = "/testConfigurationProperties")
public String testConfigurationProperties() {
log.info("test testConfigurationProperties.............{}", testConfigurationProperties.getName());
log.info("user:{}", user);
return "SUCCESS";
}
}
输出
2019-04-21/16:11:36.638||||||||^_^|[http-nio-8088-exec-1] INFO com.stone.zplxjj.controller.TestController 37 - test testConfigurationProperties.............test
2019-04-21/16:11:36.639||||||||^_^|[http-nio-8088-exec-1] INFO com.stone.zplxjj.controller.TestController 38 - user:User(id=null, name=test)
注解的原理解析
参考文章springboot(四)——@EnableConfigurationProperties是如何起作用的你知道吗