如何使用Spring加载属性文件?

时间:2019-07-12 06:35:59

标签: java spring

我很好奇要知道如何使用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后端又如何进一步加载文件?

任何人都可以分享吗?

谢谢

1 个答案:

答案 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;
}