简体   繁体   English

基于布尔变量自动装配Spring Bean

[英]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. 我想以这样的方式配置spring bean:取决于布尔变量的值,两个可用连接bean中的一个在代码中自动装配。

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:

@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 其中ConnectionOneConnectionTwo都实现了Destination

And I am using the bean in the desired class as: 我在所需的类中使用bean作为:

@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. 即使我将boolean变量的值更改为false,它也只会继续返回ConnectionOne

I am using Spring version 4.2.0 and Wildfly Server. 我使用的是Spring 4.2.0和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 我想以这样一种方式配置spring bean,这取决于布尔变量的值

The boolean variable has to be valued before the initialization of the specificConnection bean by Spring. 必须在Spring初始化specificConnection bean之前对布尔变量进行估值。 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 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. 在Spring中,您可以定义程序将运行的不同配置文件。根据您在application.properties中定义的设置,您的程序将使用这些配置文件的不同bean。 :) :)

I hope that could help you! 我希望能帮到你!

Greethings Greethings

Noixes Noixes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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