定义一堆bean的常用策略是什么,这些策略在开发和生产环境中的使用方式不同?
假设我有2个bean,每个bean实现相同的接口。一个bean用作本地文件系统的抽象,另一个bean连接到分布式文件系统。为了使开发尽可能稳定,开发环境应该使用本地文件系统实现,生产版本使用分布式文件系统bean。
目前我正在做的是有两个xml定义。
native.xml
<bean id="resourceSystem" class="com.cust.NativeResourceSystem" />
distributed.xml
<bean id="resourceSystem" class="com.cust.HadoopResourceSystem">
<constructor-arg name="fs" ref="hdfs" />
</bean>
创建应用程序上下文时,我会根据环境忽略native.xml
或distributed.xml
并抓取resourceSystem
bean。
Spring中是否有适当的工具或最佳实践来为不同的环境配置bean定义?
感谢。
答案 0 :(得分:10)
以下是Spring参考文档中关于PropertyPlaceholderConfigurer
的内容PropertyPlaceholderConfigurer不会仅在属性中查找属性 您指定的文件,,但如果找不到您尝试使用的属性,还会检查Java系统属性。
如上所示,您可以设置Java System属性
在开发机器上
-Dprofile=development
在生产机器上
-Dprofile=production
因此,您可以定义一个全局应用程序上下文设置,导入每个分层上下文设置,如下所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:property-placeholder/>
<import resource="service-${profile}.xml"/>
<import resource="persistence-${profile}.xml"/>
<import resource="security-${profile}.xml"/>
</beans>
请记住,所有位置路径都与执行导入的定义文件相关
因此,Spring支持这种配置
通常最好为这样的绝对位置保持间接,例如,通过“$ {...}”占位符在运行时针对JVM系统属性解析。
答案 1 :(得分:2)
这是我在许多项目中使用的内容。将所有与环境无关的bean放在common.xml中,将所有其他bean放在 dev.xml / qa.xml / prod.xml 中。 如果您使用ant来构建项目,那么将环境作为构建过程的参数提供,并让构建脚本包含适当的env.xml并省略其他内容。我的意思是,构建脚本将dev.xml复制为env.xml(如果是dev环境)或qa.xml复制为env.xml(如果是QA)。因此,加载bean定义的代码将始终使用“common.xml,env.xml”。
答案 2 :(得分:1)