小编典典

在不同环境下定义Spring bean的通用策略

spring

定义一堆bean的常见策略是什么,在开发和生产环境中使用的策略不同?

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

目前,我正在做的是两个xml定义。

native.xml

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

分布式.xml

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

创建应用程序上下文时,我忽略了一个native.xmldistributed.xml根据环境而定,并获取了resourceSystembean

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

谢谢。


阅读 496

收藏
2020-04-20

共1个答案

小编典典

Spring参考文档介绍了有关PropertyPlaceholderConfigurer的内容

PropertyPlaceholderConfigurer不仅会在你指定的Properties文件中查找属性,而且还会在Java System属性中检查其是否找不到你要使用的属性。

如上所示,你可以设置一个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系统属性解析的 “ $ {…}”占位符。

2020-04-20