首页 > 编程语言 > 详细

SpringBoot之@EnableConfigurationProperties

时间:2020-11-06 09:44:28      阅读:494      评论:0      收藏:0      [点我收藏+]

@EnableConfigurationProperties注解的作用是:让使用 @ConfigurationProperties 注解的类生效,并且将该类注入到Spring容器中,交由Spring容器进行管理

一、、如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化成的bean

  1、application.properties

xiaomao.name=xiaomaomao
xiaomao.age=27

  2、MyConfigurationProperties.java:这个实体类中必须要加上@Component,使这个类注入到Spring容器中,否则就无法从容器中获取到这个类的对象实例

@Component
@ConfigurationProperties(prefix = "xiaomao")
public class MyConfigurationProperties {
	// 省略 get、set、toString方法
    private String name;
    private Integer age;
    private String gender;
}

  3、HelloController.java

@RestController
public class HelloController {
    @Autowired
    private MyConfigurationProperties config;

    @GetMapping("/config")
    private String testConfigurationProperties(){
        System.out.println(config);
        return "SUCCESS!!!";
    }
}

  4、测试结果

MyConfigurationProperties{name=‘xiaomaomao‘, age=27, gender=‘null‘}

  

二、使用@EnableConfigurationProperties

  1、添加一个HelloService类

// 注入到Spring容器中,交由Spring进行管理
@Service
// 该注解的作用是使MyConfigurationProperties这个类的@ConfigurationProperties生效,并且会自动将这个类注入到Spring容器中
@EnableConfigurationProperties(MyConfigurationProperties.class)
public class HelloServiceImpl implements HelloService {
}

  2、MyConfigurationProperties.java:这个时候该实体类就不需要加上@Component注解了

@ConfigurationProperties(prefix = "xiaomao")
public class MyConfigurationProperties {
	// 省略 get、set、toString方法
    private String name;
    private Integer age;
    private String gender;
}

  3、HelloController.java

@RestController
public class HelloController {
    @Autowired
    private MyConfigurationProperties config;

    @GetMapping("/config")
    private String testConfigurationProperties(){
        System.out.println(config);
        return "SUCCESS!!!";
    }
}

  4、测试结果

MyConfigurationProperties{name=‘xiaomaomao‘, age=27, gender=‘null‘}

  

 

SpringBoot之@EnableConfigurationProperties

原文:https://www.cnblogs.com/xiaomaomao/p/13934688.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!