I want to load a specific class based on a flag instead of loading two class and using one the required in Springs

三世轮回 提交于 2019-12-24 10:40:03

问题


In configurations I have a flag isFlagEnabled.

So I have to read the flag from spring config and based on that I want to execute specific class A or B . Meaning I want to load A class only when isFlagEnabled is true and similarly load class B only when isFlagEnabled is false.

I have written the below code but i am stuck when ingesting .

public interface MediatorInt {

public void init();

}

class A implements MediatorInt {
        init() { It does some task }
    }

class B implements MediatorInt {
    init(){ It does some task }
}

public class MasterNewGenImpl {
    @Autowired
    @Qualifier("config")
    private Configuration config;

    @Autowired
    MediatorInt mediatorInt;

    private final Logger logger = Logger.getLogger(getClass());

    public void startService() {
        mediatorInt.init();
    }
}

context.xml file

  <context:component-scan base-package="com.ca"/>
    <bean id="config" class="com.ca.configuration.ConfigImplementation"/>    
    <bean id="masterSlave" class="com.ca.masterslave.A"/>
    <bean id="systemState" class="com.ca.masterslave.B"/>
    <bean id="masterSlaveNewGen" class="com.ca.masterslave.MasterNewGenImpl">
    <property name = "mediatorOrMasteSlave" value="#{config.getMediatorMode() == 'true' ? 'systemState' : 'masterSlave'}" />
</bean>

So now i am not getting how to inject specific object based on the config flag . I want to make it through Lazy-init so that other object will not get loaded when its not required . I greatly appreciate the suggestions.


回答1:


If you are okay with spring scanning both the implementations, then you can select the needed one using @Qualifier. If you want spring not to scan some class based on a property, You can use @Conditional

class SomeCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        String isFlagEnabled = context.getEnvironment().getProperty("isFlagEnabled");
        return isFlagEnabled.equals("true"));
    }
}

@Configuration
@Conditional(value = SomeCondition.class)
class A implements MediatorInt {
        init() { It does some task }
 }

In the above config, class A is scanned only if matches() in SomeCondition class returns true, where you can define the condition.




回答2:


You can use

@Autowired
@Qualifier( "systemState" )
MediatorInt systemSateMeidator;

@Autowired
@Qualifier( "masterSlave" )
MediatorInt masterSateMeidator;

With @Qualifier you are instructing spring on how to fulfill your component request.



来源:https://stackoverflow.com/questions/48681555/i-want-to-load-a-specific-class-based-on-a-flag-instead-of-loading-two-class-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!