Spring Conditional Bean creation based on another bean

I am trying to find a way to create a bean if the value of another bean / property is true using Spring 3.2 and XML config.

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

      

I've seen several similar examples using Spring EL, but nothing that does it for sure ...

+3


source to share


2 answers


You can use profiles.

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

      

You can activate several profiles at the same time or not activate them. There are several ways to activate, but to programmatically accomplish this we need to add an initializer to web.xml



<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.test.MyCustomInitializer</param-value>
</context-param>

      

MyCustomInitializer looks like this

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

      

+2


source


Why don't you use a factory to create objects when needed and make them lazy.

<bean id="second "class="xxx.xxx.Class" lazy-init="true" scope="prototype"/>

      



Can't inject if statement into spring config, profiles can work, but are more environment related than programmatic config.

0


source







All Articles