4
votes

I want to configure the spring beans in such a way that depending on the value of a boolean variable, one of the two available connection bean gets autowired in the code.

Below is the initialization of the boolean variable:

//This is overridden as false from the properties file on the server.
@Value(value = "${my.property.connectionOne:true}") 
private boolean connectionOne;

I have defined the Bean in such a way:

@Bean(name = "specificConnection")
public Destination getSpecificConnection() throws Exception {
    if (connectionOne) { //boolean variable
        return new ConnectionOne("DB");
    }
    else {
        return new ConnectionTwo("XML");
    }
}

where ConnectionOne and ConnectionTwo both implement Destination

And I am using the bean in the desired class as:

@Autowired
@Qualifier(value = "specificConnection")
private Destination specificConnection;

However, it doesn't seem to work. It keeps returning ConnectionOne only even if I change the value of the boolean variable to false.

I am using Spring version 4.2.0 and Wildfly Server.

Please let me know if any further clarification is required.

2
Show where connectionOne is initialized - Almas Abdrazak
Are you sure connectionOne boolean is false? - Betlista
Where connectionOne variable is defined and where you change it value - elmehdi
yes @Betlista, the property is overridden from the server properties file. @АлмасАбдразак please see below //This is overridden from the properties file on the server. @Value(value = "${my.property.connectionOne:true}") private boolean connectionOne; - phoenixSid
@АлмасАбдразак Edited my original code to show the declaration, since the comment was not getting formatted correctly. - phoenixSid

2 Answers

4
votes

I want to configure the spring beans in such a way that depending on the value of a boolean variable

The boolean variable has to be valued before the initialization of the specificConnection bean by Spring. So what you should probably do is using a value expression.

@Value("${isConnectionOne}") // looks the value in the available placeholder
private boolean isConnectionOne;

@Bean(name = "specificConnection")
public Destination getSpecificConnection() throws Exception {
    if (connectionOne) { //boolean variable
        return new ConnectionOne("DB");
    }
    else {
        return new ConnectionTwo("XML");
    }
}
1
votes

This is a perfect example for spring profiles! Have a look on this link:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

In Spring, you can define different profiles your program will run in. Based on settings you define in your application.properties your program will use different beans of these profiles. :)

I hope that could help you!

Greethings

Noixes