Springboot 之 @EnableConfigurationProperties 注解


@EnableConfigurationProperties 注解的作用是:讓使用了 @ConfigurationProperties 注解的類生效,並且將該類注入到 IOC 容器中,交由 IOC 容器進行管理

一、只使用 @ConfigurationProperties 注解

如果一個類只配置了 @ConfigurationProperties 注解,而沒有使用 @Component 注解將該類加入到 IOC 容器中,那么它就不能完成 xxx.properties 配置文件和 Java Bean 的數據綁定

1、application.properties

xiaomao.name=xiaomaomao
xiaomao.age=27

2、MyConfigurationProperties.java:這個實體類中必須要加上 @Component ,使這個類注入到 IOC 容器中,否則就無法從容器中獲取到這個類的對象實例

@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 類

// 注入到 IOC 容器中,交由 Spring 進行管理
@Service 
// 該注解的作用是使 MyConfigurationProperties 這個類上標注的 @ConfigurationProperties 注解生效,並且會自動將這個類注入到 IOC 容器中
@EnableConfigurationProperties(MyConfigurationProperties.class)
public class HelloServiceImpl implements HelloService {
}

2、MyConfigurationProperties.java:有了 @EnableConfigurationProperties 注解之后該實體類就不需要加上 @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'}

 

三、結論 

如果要使 xxx.properties 配置文件與 Java Bean 動態綁定,那么就必須將這個 Java Bean 加入到容器中,並且需要在該類上使用 @ConfigurationProperties 注解

@EnableConfigurationProperties(A.class)的作用就是如果 A 這個類上使用了 @ConfigurationProperties 注解,那么 A 這個類會與 xxx.properties 進行動態綁定,並且會將 A 這個類加入 IOC 容器中,並交由 IOC 容器進行管理

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM