spring boot 注入 property的三种方式


声明:本文转载自https://my.oschina.net/u/778875/blog/1359216,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

            以前使用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。现在使用@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。只是现在的配置是用@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; 	} 	 } 

本文发表于2017年07月13日 18:36
(c)注:本文转载自https://my.oschina.net/u/778875/blog/1359216,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 2063 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1