spring boot 注入 property的三種方式(推薦)
以前使用spring的使用要注入property要配置PropertyPlaceholder的bean對象。在springboot除 了這種方式以外還可以通過制定 配置ConfigurationProperties直接把property文件的 屬性映射到 當前類里面。
@ConfigurationProperties(prefix = "mypro", merge = true, locations = { "classpath:my.properties" })
ConfigurationProperties prefix 屬性指示property文件中屬性的前綴是什么。我這里寫的是mypro。
因此property文件的屬性必須mypro.x.y=z的形式;
配置好ConfigurationProperties 之后就可以把property文件的屬性映射到當前類了。
mypro.a:1 mypro.b:2 abc.d:123
property 文件里面mypro前綴的有a 和b兩個。因此我在當前類就可以新建這兩個屬性。
private int a; private int b;
這些需要映射的屬性一定要加上getter 和setter。因為spring是通過反射調用方法來修改屬性值的
以前使用spring注入property的方式也同樣適用。以前是xml配置PropertyPlaceholder?,F(xiàn)在使用@bean 或者直接@Component配置這個類。只要把PropertyPlaceholderConfigurer添加到bean工廠,就可以使用@Value 取值了。
@Component public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{ public MyPropertyPlaceholderConfigurer(){ this.setIgnoreResourceNotFound(true); final List<Resource> resourceLst = new ArrayList<Resource>(); resourceLst.add(new ClassPathResource("my.properties")); this.setLocations(resourceLst.toArray(new Resource[]{})); } } @Value("abc.d") private String test;
另外的一種方法跟第二種差不多的。更像以前的xml配置PropertyPlaceholder。只是現(xiàn)在的配置是用@Configuration標注的類,用@Bean標注要配置的bean對象;
@Configuration public class Testproperties { @Bean public PropertyPlaceholderConfigurer properties(){ final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setIgnoreResourceNotFound(true); final List<Resource> resourceLst = new ArrayList<Resource>(); resourceLst.add(new ClassPathResource("my.properties")); ppc.setLocations(resourceLst.toArray(new Resource[]{})); return ppc; } }
以上所述是小編給大家介紹的spring boot 注入 property的三種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Spring如何使用PropertyPlaceholderConfigurer讀取文件
- Spring Boot中@ConditionalOnProperty的使用方法
- Spring @value和@PropertySource注解使用方法解析
- Spring Boot自定義配置屬性源(PropertySource)
- Spring中property-placeholder的使用與解析詳解
- Spring boot中PropertySource注解的使用方法詳解
- 詳解Spring Boot 自定義PropertySourceLoader
- spring-core組件詳解——PropertyResolver屬性解決器
- Spring框架讀取property屬性文件常用5種方法
相關文章
Java簡單計時的實現(xiàn)案例(可以用來限時循環(huán))
這篇文章主要介紹了Java簡單計時的實現(xiàn)案例(可以用來限時循環(huán)),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08Springboot使用Redis中ZSetOperations實現(xiàn)博客訪問量
在日常的網(wǎng)站使用中,經(jīng)常會碰到頁面的訪問量,本文主要介紹了Springboot使用Redis中ZSetOperations實現(xiàn)博客訪問量,具有一定的參考價值,感興趣的可以了解一下2024-01-01Java8新特性Optional類處理空值判斷回避空指針異常應用
這篇文章主要介紹了Java8新特性Optional類處理空值判斷回避空指針異常應用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04解決偶現(xiàn)的MissingServletRequestParameterException異常問題
這篇文章主要介紹了解決偶現(xiàn)的MissingServletRequestParameterException問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10