且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在运行时从属性文件中读取值

更新时间:2022-12-05 22:48:07

使用 PropertiesFactoryBean 注入 Bean 中的属性.

<bean id="myPropertiesBean"
  class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:ErrorMessage.properties"/>
</bean>

这提供了一个 属性 可以在任何 Bean 中以 myPropertiesBean 名称注入的对象/Bean (<property name="x" ref="myPropertiesBean"/>).

This provides a Properties Object/Bean which can be injected under the name myPropertiesBean in any Bean (<property name="x" ref="myPropertiesBean"/>).

此外 Spring 提供了 util 命名空间(自 Spring 2.5 起):在那里你可以编写更短的 PropertyFactoryBean 定义:

In addition Spring provides the util namespace (since Spring 2.5): There you can write the PropertyFactoryBean definition a bit shorter:

<util:properties id="myPropertiesBean"
 location="classpath:ErrorMessage.properties"/>

@see Spring 参考章节 C.2.2.3.