Autowire Spring Bean Based on Boolean Variable

I want to configure spring beans so that, depending on the value of the boolean variable, one of the two available bean connections is automatically transferred to the code.

The following is the initialization of a boolean variable:

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

I defined a bean this way:

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

where ConnectionOnethey ConnectionTworealizeDestination

And I use bean in the desired class as:

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

However, it does not work. It keeps returning ConnectionOneeven if I change the value of a 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.

+4
source share
2 answers

spring beans ,

specificConnection bean Spring. , , , , .

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

spring! :

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

Spring , . , .properties beans .:)

, !

Greethings

Noixes

+1

Source: https://habr.com/ru/post/1693513/


All Articles