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。现在使用@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;
	}
	
}

									

作者:大汉刺史

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值