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;
	}
	
}
相关文章
相关标签/搜索