Java 基于另一个Bean创建Spring条件Bean
我试图找到一种方法,使用Spring3.2和XML配置,仅当另一个bean/属性的值为true时,才创建一个beanJava 基于另一个Bean创建Spring条件Bean,java,xml,spring,spring-el,Java,Xml,Spring,Spring El,我试图找到一种方法,使用Spring3.2和XML配置,仅当另一个bean/属性的值为true时,才创建一个bean <bean id="isEnabled" class="java.lang.Boolean"> <bean factory-bean="configurationService" factory-method="getBooleanValue"> <constructor-arg index="0">
<bean id="isEnabled" class="java.lang.Boolean">
<bean factory-bean="configurationService" factory-method="getBooleanValue">
<constructor-arg index="0">
<util:constant static-field="org.code.ConfigurationKeys.ENABLED"/>
</constructor-arg>
</bean>
</bean>
<if isEnabled=true>
..... create some beans
</if>
..... 制作一些豆子
我见过一些使用Spring EL的稍微相似的例子,但没有什么能做到这一点…为什么不在需要时使用工厂来创建对象,并使它们变得懒惰
<bean id="second "class="xxx.xxx.Class" lazy-init="true" scope="prototype"/>
没有办法在spring配置中引入if语句,概要文件可以工作,但与环境更相关,而不是编程配置。您可以使用概要文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd" >
<!-- here goes common beans -->
<beans profile="Prof_1">
<import resource="./first-config.xml" />
</beans>
<beans profile="Prof_2">
<import resource="./second-config.xml" />
</beans>
</beans>
可以同时激活多个配置文件,也可以选择不激活任何配置文件。激活有多种方法,但要通过编程实现这一点,我们需要在web.xml中添加初始值设定项
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.test.MyCustomInitializer</param-value>
</context-param>
上下文初始化类
com.test.MyCustomInitializer
MyCustomInitializer如下所示
public class MyCustomInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
String activeProf;
// some logic to either read file/env variable/setting to determine which profile to activate
applicationContext.getEnvironment().setActiveProfiles( activeProf );
} catch (IOException e) {
e.printStackTrace();
}
}
}
公共类MyCustomInitializer实现ApplicationContextInitializer{
@凌驾
public void初始化(ConfigurableApplicationContext applicationContext){
试一试{
字符串activeProf;
//读取文件/env变量/设置以确定要激活的配置文件的一些逻辑
applicationContext.getEnvironment().setActiveProfiles(activeProf);
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
你能提供更多关于实际用例的详细信息吗?我知道你的问题已经有一段时间了,但是如果你还没有找到答案,也许Sprint概要文件功能可以作为这项工作的工具。使用Spring java配置和@Conditional
注释来实现它非常简单。但是,如果xml配置非常重要,您可以阅读以下文章: