Der*_*har 10 java spring properties classpath
如何配置Spring bean容器(或应用程序上下文)来加载Java属性文件?
JavaWorld文章Smartly Load Your Properties说明了如何使用标准Java库中的以下资源处理方法之一从类路径加载属性文件:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
Class.getResourceAsStream ("/some/pkg/resource.properties");
ResourceBundle.getBundle ("some.pkg.resource");
Run Code Online (Sandbox Code Playgroud)
你如何使用Spring bean容器做同样的事情?
Der*_*har 16
在Spring框架参考文档(2.5.X)给出了如何将属性文件加载到一个bean的容器,一个2.5版本的发布和使用更简洁的方式前两个例子<util:properties/>功能是在2.5版本中引入的:
2.5版之前:
<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:com/foo/jdbc-production.properties"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
版本2.5之后:
<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<util:properties id="jdbcConfiguration" location="classpath:com/foo/jdbc-production.properties"/>
Run Code Online (Sandbox Code Playgroud)
请注意,为了使用<util:properties/>,您必须util在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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<!-- <bean/> definitions here -->
</beans>
Run Code Online (Sandbox Code Playgroud)
你的beans.xml文件应该有PropertyPlaceholderConfigurer:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:some/pkg/resource.properties</value>
</list>
</property>
<!-- Default values for backwards compatibility -->
<property name="properties">
<props>
<prop key="name">value</prop>
</props>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
然后你可以在下面的其他地方引用这些属性beans.xml:
<bean class="${blah}">
....
<bean>
Run Code Online (Sandbox Code Playgroud)
有关此内容的文章,请查看http://almaer.com/blog/spring-propertyplaceholderconfigurer-a-nice-clean-way-to-share
例如,通过PropertiesFactoryBean.使用PropertyPlaceholderConfigurer通过属性在上下文中配置bean.
您将在其他答案中找到PropertyPlaceholderConfigurer示例.这是一个PropertiesFactoryBean示例:
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value=classpath:config/applicationConfig.properties"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54708 次 |
| 最近记录: |