spring-boot-configuration-processor


spring默認使用yml中的配置,但有時候要用傳統的xml或properties配置,就需要使用spring-boot-configuration-processor了

引入pom依賴

 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>

 

author.name=zhangsan author.age=20

再在配置類開頭加上@PropertySource("classpath:your.properties"),其余用法與加載yml的配置一樣

@Component @PropertySource(value = {"classpath:static/config/authorSetting.properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties") public class AuthorTest { @Value("${author.name}") private String name; @Value("${author.age}") private int age; } 

@PropertySource 中的屬性解釋 
1.value:指明加載配置文件的路徑。 
2.ignoreResourceNotFound:指定的配置文件不存在是否報錯,默認是false。當設置為 true 時,若該文件不存在,程序不會報錯。實際項目開發中,最好設置 ignoreResourceNotFound 為 false。 
3.encoding:指定讀取屬性文件所使用的編碼,我們通常使用的是UTF-8。

當我們使用 @Value 需要注入的值較多時,代碼就會顯得冗余,於是 @ConfigurationProperties 登場了

@Component @ConfigurationProperties(prefix = "author") @PropertySource(value = {"classpath:static/config/authorSetting.properties"}, ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties") public class AuthorTest { private String name; private int age; } 
@RestController @EnableConfigurationProperties public class DemoController { @Autowired AuthorTest authorTest; @RequestMapping("/") public String index(){ return "author's name is " + authorTest.getName() + ",ahtuor's age is " + authorTest.getAge(); } } 

使用 @EnableConfigurationProperties 開啟 @ConfigurationProperties 注解。


免責聲明!

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



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