spring boot 注入 property的三種方式

            之前使用spring的使用要注入property要配置PropertyPlaceholder的bean對象。在springboot除  了這種方式之外還能夠經過制定 配置ConfigurationProperties直接把property文件的 屬性映射到 當前類裏面。java

@ConfigurationProperties(prefix = "mypro", merge = true, locations = { "classpath:my.properties" })

ConfigurationProperties prefix 屬性指示property文件中屬性的前綴是什麼。我這裏寫的是mypro。spring

所以property文件的屬性必須mypro.x.y=z的形式;springboot

     配置好ConfigurationProperties 以後就能夠把property文件的屬性映射到當前類了。this

mypro.a:1
mypro.b:2
abc.d:123

property 文件裏面mypro前綴的有a 和b兩個。所以我在當前類就能夠新建這兩個屬性。spa

private int a;
	private int b;

這些須要映射的屬性必定要加上getter 和setter。由於spring是經過反射調用方法來修改屬性值的.net

 

 

        之前使用spring注入property的方式也一樣適用。之前是xml配置PropertyPlaceholder。如今使用@bean 或者直接@Component配置這個類。只要把PropertyPlaceholderConfigurer添加到bean工廠,就能夠使用@Value 取值了。code

@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對象;xml

@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;
	}
	
}
相關文章
相關標籤/搜索