以前使用spring的使用要注入property要配置PropertyPlaceholder的bean對象。在springboot除 了這種方式以外還可以通過制定 配置ConfigurationProperties直接把property文件的 屬性映射到 當前類里面。
1
|
@ConfigurationProperties (prefix = "mypro" , merge = true , locations = { "classpath:my.properties" }) |
ConfigurationProperties prefix 屬性指示property文件中屬性的前綴是什么。我這里寫的是mypro。
因此property文件的屬性必須mypro.x.y=z的形式;
配置好ConfigurationProperties 之后就可以把property文件的屬性映射到當前類了。
1
2
3
|
mypro.a: 1 mypro.b: 2 abc.d: 123 |
property 文件里面mypro前綴的有a 和b兩個。因此我在當前類就可以新建這兩個屬性。
1
2
|
private int a; private int b; |
這些需要映射的屬性一定要加上getter 和setter。因為spring是通過反射調用方法來修改屬性值的
以前使用spring注入property的方式也同樣適用。以前是xml配置PropertyPlaceholder。現在使用@bean 或者直接@Component配置這個類。只要把PropertyPlaceholderConfigurer添加到bean工廠,就可以使用@Value 取值了。
1
2
3
4
5
6
7
8
9
10
11
|
@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。只是現在的配置是用@Configuration標注的類,用@Bean標注要配置的bean對象;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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的三種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://my.oschina.net/u/778875/blog/1359216