Spring Qualifier name based on the spring profile in Spring MVC

911 Views Asked by At

In my Spring Config, I have defined three beans as following.

   <bean id="validationFlag-dev" class="java.lang.Boolean">
        <constructor-arg value="false"/>
    </bean>
    <bean id="validationFlag-test" class="java.lang.Boolean">
        <constructor-arg value="true"/>
    </bean>
    <bean id="validationFlag-prod" class="java.lang.Boolean">
        <constructor-arg value="true"/>
    </bean>

In my service, I would like to @Autowired the bean based on the spring profile. I'm trying as per below to define the qualifier name based on the active spring profile but it is giving an error cannot find bean with qualifier. How can i handle Qualifier name in this situation in spring MVC. Please advise.

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

There are 2 best solutions below

0
On

You're not using profiles correctly. You should instantiate one bean, not every bean for every profile, and do that based on what profile's active.

For example:

<beans profile="dev">
  <bean id="validationFlag" class="java.lang.Boolean">
    <constructor-arg value="false"/>
  </bean>
</beans>

Then just autowire this way:

@Autowired
@Qualifier("validationFlag")
Boolean validationFlag;
0
On

Maybe in your case easier solution will be to add this flag as a property.

Just create property file for each profile.
e.g. for dev profile create application-dev.properties and set property validation.flag=false

To retrieve this flag, use

@Value("{validation.flag}") Boolean validFlag;