关于@EnableConfigurationProperties注解的使用

@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

  • 24
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值