栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

关于@EnableConfigurationProperties注解的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于@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 maps;
    private List 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 maps;
    private List 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

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号