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

标签 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 类加载。

locationsPropertyPlaceholderConfigurer类中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/

相关文章:

java - 如何使用迭代器从通用 ArrayList 中获取对象?

java - 为什么 Oracle 声称 java.util.Random.nextFloat() 生成 2^24 种可能性而不是 2^23 种?

java - Spring Autowiring 和原型(prototype)范围

java - 在运行时配置生存时间属性

java - 基于元素值的子 ListView

java - ehcache session 范围在 grails 中

java - 在有限的空间内显示图像的特定部分?

java - 使用 java spring 应用程序进行 SAP RFC 调用

java - Spring 框架到底是干什么用的?

java - 如何使用gmail smtp发送邮件Spring实现?