代码之家  ›  专栏  ›  技术社区  ›  Juraj Blahunka

针对不同环境定义SpringBeans时的常见策略

  •  7
  • Juraj Blahunka  · 技术社区  · 14 年前

    定义一组bean的常用策略是什么,这些bean在开发和生产环境中的使用方式不同?

    假设我有两个bean,每个bean实现相同的接口。一个bean用作本地文件系统的抽象,另一个连接到分布式文件系统。为了尽可能保持开发的稳定,开发环境应该使用本地文件系统实现,生产版本使用分布式文件系统bean。

    目前我正在做的是有两个XML定义。

    n.xml

    <bean id="resourceSystem" class="com.cust.NativeResourceSystem" />
    

    分布式XML

    <bean id="resourceSystem" class="com.cust.HadoopResourceSystem">
        <constructor-arg name="fs" ref="hdfs" />
    </bean>
    

    在创建应用程序上下文时,我忽略了 native.xml distributed.xml 视环境而定,抓住 resourceSystem 豆类。

    Spring中是否有合适的工具或最佳实践来为不同的环境配置bean定义?

    谢谢。

    3 回复  |  直到 14 年前
        1
  •  10
  •   Arthur Ronald    14 年前

    下面是Spring参考文档所说的内容 PropertyPlaceholderConfigurer

    PropertyPlaceHolderConfigurator不只在属性中查找属性 指定的文件, 还要检查Java系统的属性。 如果找不到您要使用的属性。

    正如上面所看到的,您可以设置Java系统属性。

    在开发机器上

    -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>
    

    记住所有位置路径 与执行导入的定义文件相关

    因此,这种配置由弹簧支撑。

    通常情况下,最好保持这种绝对位置的间接性,例如,通过“$…”占位符。 在运行时根据JVM系统属性进行解析 .

        2
  •  2
  •   chedine    14 年前

    这就是我在许多项目中使用的方法。在say common.xml中使用所有与环境无关的bean,在say中使用所有其他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”。

        3
  •  1
  •   earldouglas    14 年前

    这项功能在SpringSource的雷达上,并计划在未来发布。

    here here .