首页 > 解决方案 > 如何使用 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 接口的类的实例名。这是对的吗?ResourcePropertyPlaceholderConfigurerclasspath*:application.properties

如果是,那么在那之后,spring 后端如何进一步加载文件?

请问有人可以分享吗?

谢谢

标签: javaspring

解决方案


是的,你是对的,这是xml配置的相应java代码,在将属性文件加载到spring环境之后。通过使用java.reflectionspring 将值注入到 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;
}

推荐阅读