javajboss-weld

JBoss Weld : Inject different implementation for testing


I would like to inject a different implementation in a bean, depending on the context. Here is the situation :

interface A{}

class AImplForTest implements A{}

class AImplForProd implements A{}

class B{
    @Inject A a;
}

In a test context, I would like the AImplForTest to be injected, while in a production context, this should be AImplForProd. B is the same class in the two contexts. Is it possible?


Solution

  • Never used in practice but from theory you could use the @Alternative annotation.

    From the Weld reference documentation:

    Alternatives are beans whose implementation is specific to a particular client module or deployment scenario. ... By default, @Alternative beans are disabled. We need to enable an alternative in the beans.xml descriptor of a bean archive to make it available for instantiation and injection. This activation only applies to the beans in that archive.