0

I have a bean with a 3-arg and a 4-arg constructor. Based on local or cloud condition it has to create the bean. If local, initialize the bean using 3-arg constructor else use the 4-arg constructor.

I created LocalCondition and RemoteCondition and both read an env property(isRemote=true/false) and based on that Bean is created. In my spring configuration I have like shown below. But it works only when one of DeploymentBean is commented out.

public class LocalCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context,
                           AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return null != env
                && "false".equals(env.getProperty("isRemote"));
    }
}

public class RemoteCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context,
                           AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return null != env
                && "true".equals(env.getProperty("isRemote"));
    }
}

Then annotated beans:

@Bean
@Conditional(LocalCondition.class)
public DeploymentBean deploymentBean() {
    new DeploymentBean(3 args)
}

@Bean
@Conditional(RemoteCondition.class)
public DeploymentBean deploymentBean() {
    new DeploymentBean(3 args and RemoteConfigBean)
}

@Bean
@Conditional(RemoteCondition.class)
public RemoteConfigBean deploymentBean() {
    new RemoteConfigBean()
}

I dont want to comment out one DeploymentBean to flip my logic. But that is the only option right now.

0 Answers0