imoteb imoteb - 1 year ago 120
Java Question

Java Spring Autowiring with profile

I have a class lets say class A which is a Configuration class and runs only when profile "production" is activated. But in class B where the main logic of the application is I am using @Autowired annotation that refers to some bean that is created in class A, my problem is when for example I run the application with profile lets say "default" it throws exception because the appropiate bean is not created. So my question is how I can use this Autowired in my class B only when profile "production" is active ?

Answer Source

Providing you have two implementations of A interface:

public interface A {}

public class ADev implements A {}

public class AProd implements A {}

public class B {
    @Autowired @Qualifier("A") A a;

Add an XML config with alias and a property placeholder:

    <alias name="${a.class}" alias="A"/>
    <context:property-placeholder location=""/>
<beans> should contain


Then changing propertiy will change your injected class (app restart would be required).

There are other solutions such as:

  • Filtering XML context with maven (build time)
  • Creating a bean factory which returns different A implementations depending on something
  • Using spring EL #{expression}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download