Java 是否可以在运行时指定上下文属性占位符
我有一个使用spring的独立jar。SpringXML中的配置使用了占位符,我在用maven编译时一直在替换占位符。spring配置示例:Java 是否可以在运行时指定上下文属性占位符,java,spring,properties,Java,Spring,Properties,我有一个使用spring的独立jar。SpringXML中的配置使用了占位符,我在用maven编译时一直在替换占位符。spring配置示例: <bean id="foo" class="package.Foo"> <property name="host" value="${db.host}" /> </bean> 这将允许我通过传入生产数据库属性文件或测试数据库属性文件,在运行时切换数据库主机 有没有可能做到这一点,或者有没有更好的方法来实现相同的
<bean id="foo" class="package.Foo">
<property name="host" value="${db.host}" />
</bean>
这将允许我通过传入生产数据库属性文件或测试数据库属性文件,在运行时切换数据库主机
有没有可能做到这一点,或者有没有更好的方法来实现相同的目标?您可以使用
PropertyPlaceHolderConfigure
来使用.properties
文件来传递所需的变量
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:productionDB.properties</value>
</list>
</property>
</bean>
类路径:productionDB.properties
您可以让bean声明保持原样。属性将自动从
productionDB.properties
文件中获取。您可以使用PropertyPlaceHolderConfigure
来使用.properties
文件传递所需的变量
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:productionDB.properties</value>
</list>
</property>
</bean>
类路径:productionDB.properties
您可以让bean声明保持原样。属性将自动从productionDB.properties文件中获取。有几个选项:
。与“完整”bean定义相比,我更喜欢这种简写,因为Spring将自动使用正确的实现(PropertyPlaceHolderConfigure
用于Spring<3.1),或者PropertySourcePlaceHolderConfigurer
用于Spring 3.1+)。使用此配置,只需将myProps.properties
放在类路径的根目录下(例如${TOMCAT\u HOME}/lib
)有几种选择:
。与“完整”bean定义相比,我更喜欢这种简写,因为Spring将自动使用正确的实现(PropertyPlaceHolderConfigure
用于Spring<3.1),或者PropertySourcePlaceHolderConfigurer
用于Spring 3.1+)。使用此配置,只需将myProps.properties
放在类路径的根目录下(例如${TOMCAT\u HOME}/lib
)您可以将属性文件指定为系统属性,例如:
java -jar Application.jar -DappConfig=/path/to/productionDB.properties
然后,您应该能够在应用程序上下文中引用:
您可以将属性文件指定为系统属性,例如:
java -jar Application.jar -DappConfig=/path/to/productionDB.properties
然后,您应该能够在应用程序上下文中引用:
您可以使用context:property占位符传递值。因此,您的设置类似于:
<context:property-placeholder location="file://opt/db.properties"/>
然后,在连接Foo服务时,可以在配置中使用属性名称,例如
<bean id="foo" class="package.Foo">
<property name="host" value="${db.host}" />
</bean>
然后对每个环境使用不同的文件集
有关更多详细信息,请参阅文档 可以使用context:property占位符传递值。因此,您的设置类似于:
<context:property-placeholder location="file://opt/db.properties"/>
然后,在连接Foo服务时,可以在配置中使用属性名称,例如
<bean id="foo" class="package.Foo">
<property name="host" value="${db.host}" />
</bean>
然后对每个环境使用不同的文件集
有关更多详细信息,请参阅文档 使用数据源xml可能是更改DataSecan的好主意您可以共享applicationcontext配置使用数据源xml可能是更改DataSecan的好主意您可以共享applicationcontext配置