简体   繁体   中英

Autowire a bean from spring config - Environment specific

I'm trying to have environment specific boolean flag. In my spring config, I defined three beans which are environment specific as per below.

    <bean id="validationFlag-E1" class="java.lang.Boolean.FALSE"/>
    <bean id="validationFlag-E2" class="java.lang.Boolean.TRUE"/>
    <bean id="validationFlag-E3" class="java.lang.Boolean.TRUE"/>

I have also "spring.profiles.active" system property defined at server level and its value is "E1 /E2 /E3" based on the environment.

In my service, i'm trying to do autowiring as per below but it is not working and getting No qualifying bean of type 'java.lang.Boolean' available: expected at least 1 bean which qualifies as autowire candidate. Please advise me.

@Autowired
@Qualifier("validationFlag-${spring.profiles.active}")
Boolean evalFlag;

We can achieve the above requirement by having individual environment specific property file. But I don't want to create three property files for a single flag. So, trying above approach in my spring framework project.

You can use environmental property ${blah.blah.flag} (or whatever name you choose) with value of a flag ( false or true ) -Dblah.blah.flag=true and then inject that value as a property

@Value("${blah.blah.flag}")
private Boolean flag;

Change your bean definition to:

<bean id="validationFlag-E1" class="java.lang.Boolean">
     <constructor-arg value="false"/>
</bean>
    <bean id="validationFlag-E2" class="java.lang.Boolean">
<constructor-arg value="true"/>
</bean>
    <bean id="validationFlag-E3" class="java.lang.Boolean">
<constructor-arg value="true"/>
</bean>

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