简体   繁体   中英

Autowire Spring Bean based on boolean variable

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM