编程语言
首页 > 编程语言> > java-基于另一个bean的Spring条件Bean创建

java-基于另一个bean的Spring条件Bean创建

作者:互联网

我正在尝试找到一种使用Spring 3.2和XML配置仅在另一个bean /属性的值为true时创建一个bean的方法.

<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的稍微相似的示例,但是却没有做到这一点……

解决方法:

您可以使用配置文件.

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

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();
        }
    }
}

标签:spring-el,xml,spring,java
来源: https://codeday.me/bug/20191120/2047908.html