以前使用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的三种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
原文链接:https://my.oschina.net/u/778875/blog/1359216
相关文章
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-27 79
-
2025-05-27 36
-
2025-05-27 101
-
2025-05-25 31
-
2025-05-29 82

