我很好奇要知道如何使用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
是类Resource
中类型为PropertyPlaceholderConfigurer
的实例变量。因此,以上示例classpath*:application.properties
中的值是实现Resource接口的class的实例名称。正确吗?
如果是,那么之后,Spring后端又如何进一步加载文件?
任何人都可以分享吗?
谢谢
答案 0 :(得分:1)
是的,这是对的,这是将属性文件加载到spring环境之后的xml config的相应Java代码。通过使用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;
}