springboot中的注解-EnableConfigurationProperties

参考文章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是如何起作用的你知道吗

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值