Показаны сообщения с ярлыком J2EE 6. Показать все сообщения
Показаны сообщения с ярлыком J2EE 6. Показать все сообщения

пятница, 31 июля 2015 г.

J2EE. Logging in application

Logging is an cross-cutting concern in the application.

It is tedious to write every time

Logger log = LogManager.getLogger(getClass()); 

To speed up one can copy this string from one class to another.
Not very expressive way. Well, it is more code to read.
Nowadays we have annotations, we have EJB, we have CDI.

We can improve the logging code in two ways:
  1. implement the logging as a cross-cutting concern with a CDI interceptor
  2. if we need more logging it would be much simpler to inject logger

четверг, 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.