четверг, 30 июля 2015 г.

J2EE6. CDI qualifier convenient injection

When you have an interface reference in a class and this interface has more than 1 implementation you have to specify somehow the injected implementation.

CDI offers you the qualifiers mechanism (annotations) to resolve this issue. For example you can create one annotation for PROD version and another annotation for TEST version of the implementation. Two annotations for such a thing are too much.

We can simplify it.

Here is our qualifier:
@Qualifier
@Retention(RUNTIME)
@Target({ FIELD, TYPE, METHOD })
public @interface ConnectionFactory {
    ConnectionFactoryType value();
}

Here is the example of ConnectionFactoryType:
 public enum ConnectionFactoryType {
    PROD, TEST
}

 Here is how how the implementation of the CDI bean looks like:
@ConnectionFactory(ConnectionFactoryType.PROD)
@ApplicationScoped
public class ProdConnectionFactory implements IConnectionFactory {}



Here is how you inject the bean:
@Inject
@ConnectionFactory(ConnectionFactoryType.PROD)
private IConnectionFactory connectionFactory;

What we got here is:
1) we created one annotation for different connection implementations.
2) We can specify the implementation by specifying the enum value.
3) This is reusable and better then creating one annotation per implementation.


Комментариев нет:

Отправить комментарий