如何使用 Spring 加载属性文件



我很想知道apllication.properties文件或任何其他属性文件是如何使用Spring加载的。

这是执行此操作的 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 是类 PropertyPlaceholderConfigurerResource 类型的实例变量。因此,上面示例中的值classpath*:application.properties是实现资源接口的类的实例名称。正确吗?

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

任何人都可以分享吗?

谢谢

是的,你是对的,这是 xml 配置的相应 java 代码,在将属性文件加载到 spring 环境中后。通过使用java.reflection弹簧会将值注入春豆中。

@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;
}