我很想知道如何使用 Spring 加载 apllication.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
是PropertyPlaceholderConfigurer
类中Resource
类型的实例变量。所以上面例子中的值 classpath*:application.properties
是一个实现 Resource 接口(interface)的类的实例名。是否正确?
如果是,那么在那之后,如何在 spring 后端进一步加载文件?
有人可以分享吗?
谢谢
最佳答案
是的,你是对的,这是 xml 配置的相应 java 代码,在将属性文件加载到 spring 环境之后。通过使用 java.reflection
spring 会将值注入(inject) 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;
}
关于java - 如何使用 Spring 加载属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57001386/