java - 如何使用 Spring 加载属性文件?
问题描述
我很想知道如何使用 Spring 加载 appllication.properties 文件或任何其他属性文件。
这是执行此操作的 XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "myProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:application.properties</value>
</list>
</property>
</bean>
</beans>
如您所见,application.properties
文件正在使用PropertyPlaceholderConfigurer
该类加载。
并且是类locations
中类型的实例变量。所以上面例子中的值是一个实现 Resource 接口的类的实例名。这是对的吗?Resource
PropertyPlaceholderConfigurer
classpath*:application.properties
如果是,那么在那之后,spring 后端如何进一步加载文件?
请问有人可以分享吗?
谢谢
解决方案
是的,你是对的,这是xml配置的相应java代码,在将属性文件加载到spring环境之后。通过使用java.reflection
spring 将值注入到 spring bean 中。
@Bean
public static PropertyPlaceholderConfigurer myProperties() {
PropertyPlaceholderConfigurer ppc
= new PropertyPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[]
{ new ClassPathResource( "application.properties" ) };
ppc.setLocations( resources );
ppc.setIgnoreUnresolvablePlaceholders( true );
return ppc;
}
推荐阅读
- nunit - 使 NUnit3 在整个测试套件中最后运行指定的测试
- javascript - 从 Flask 发送时,Javascript 变量正在更改编码
- sonarqube - 具有多个 SonarQube 实例时未列出 SonarQube 问题
- wordpress - Woocommerce 产品数据部分搞砸了。如何解决?
- python - 列表总和的绝对值
- django - 无法导入 'django.contrib'pylint(导入错误)
- python - 计算两种 24 小时时间格式之间的小时数
- internet-explorer - 关闭特定子站点的兼容性视图 - 它是在组策略中设置的
- reactjs - 在@apollo/react-hooks 的 useQuery 钩子中忽略了跳过参数
- python - Pearsonr:TypeError:没有找到与指定签名和转换匹配的循环,用于 ufunc add