是否可以在 Spring 配置中使用条件表达式?
例如。我想定义两个不同的连接器,如下所示:
连接器 1:
<spring:bean id="MyConnector" class="org.test.provider.DBConnector">
<spring:property name="host" value="${my.config.host}"/>
<spring:property name="user" value="${my.config.user}"/>
<spring:property name="password" value="${my.config.password}"/>
</spring:bean>
连接器 2:
<spring:bean id="MyConnector" class="org.test.provider.FileSystemConnector">
<spring:property name="path" value="${my.config.path}"/>
</spring:bean>
然后,稍后使用如下其中之一:
<spring:bean id="LookupCommand" class="org.test.lookup.LookupCommand"
scope="prototype">
<spring:property name="connector" ref="MyConnector"/>
</spring:bean>
可以说,取决于,${my.config.connectorType}
从我的 .cfg 文件中,我想选择/激活这两个文件之一:
if ${my.config.connectorType} == DB then
<spring:bean id="MyConnector" class="org.test.provider.DBConnector">
<spring:property name="host" value="${my.config.host}"/>
<spring:property name="user" value="${my.config.user}"/>
<spring:property name="password" value="${my.config.password}"/>
</spring:bean>
else
<spring:bean id="MyConnector" class="org.test.provider.FileSystemConnector">
<spring:property name="path" value="${my.config.path}"/>
</spring:bean>
end
...
<spring:bean id="LookupCommand" class="org.test.lookup.LookupCommand"
scope="prototype">
<spring:property name="connector" ref="MyConnector"/>
</spring:bean>
一个简单的替代解决方案。为每个连接器指定不同的名称,如下所示
<spring:bean id="dbConnector" class="org.test.provider.DBConnector">
<spring:property name="host" value="${my.config.host}"/>
<spring:property name="user" value="${my.config.user}"/>
<spring:property name="password" value="${my.config.password}"/>
</spring:bean>
<spring:bean id="fileConnector" class="org.test.provider.FileSystemConnector">
<spring:property name="path" value="${my.config.path}"/>
</spring:bean>
在属性文件中,指定要连接的连接器的名称,例如 my.config.connectorType=dbConnector
在 LookupCommand bean 中,引用此属性,如下所示
<spring:bean id="LookupCommand" class="org.test.lookup.LookupCommand"
scope="prototype">
<spring:property name="connector" ref="${my.config.connectorType}"/>
</spring:bean>
注:我最初想到建议bean 定义概要文件 http://spring.io/blog/2011/02/11/spring-framework-3-1-m1-released#enter-bean-definition-profiles但你必须传递系统属性-Dspring.profiles.active
在你的 JVM 中。我试图避免这种情况,并且在上述方法中,您无需麻烦地设置任何 JVM 系统属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)