Java EE 8 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Implementing the TransactionFactory class

In the following code, we have the Transactional annotation, which is a Qualifier used to inject the Transaction class:

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Transactional {
}

In the preceding code block, we have the TransactionFactory class, which is responsible for creating new instances of the Transaction class. This class uses the @Singleton annotation, which is an EJB annotation used to create a singleton pattern with the Java EE mechanism. The getTransaction method has the @Produces annotation, used to define a method responsible for creating a new instance, and the @Transactional annotation, used as a qualify:

import javax.ejb.Singleton;
import javax.enterprise.inject.Produces;

@Singleton
public class TransactionFactory {

public @Produces @Transactional Transaction getTransaction(){
//Logic to create Transations.
return new Transaction();
}
}