imoteb imoteb - 2 months ago 7
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

Providing you have two implementations of A interface:

public interface A {}

@Component(value="A_dev")
public class ADev implements A {}

@Component(value="A_prod")
public class AProd implements A {}

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

Add an XML config with alias and a property placeholder:

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

app.properties should contain

a.class=A_dev

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}