Using Predefined Beans in CDI Applications
CDI provides predefined beans that implement the following interfaces:
- javax.transaction.UserTransaction
A Java Transaction API (JTA) user transaction.
- java.security.Principal
The abstract notion of a principal, which represents any entity, such as an individual, a corporation, or a login ID. Whenever the injected principal is accessed, it always represents the identity of the current caller. For example, a principal is injected into a field at initialization. Later, a method that uses the injected principal is called on the object into which the principal was injected. In this situation, the injected principal represents the identity of the current caller when the method is run.
- javax.validation.Validator
A validator for bean instances. The bean that implements this interface enables a Validator object for the default bean validation ValidatorFactory object to be injected.
- javax.validation.ValidatorFactory
A factory class for returning initialized Validator instances. The bean that implements this interface enables the default bean validation object ValidatorFactory to be injected.
To inject a predefined bean, create an injection point by using the javax.annotation.Resource annotation to obtain an instance of the bean. For the bean type, specify the class name of the interface the bean implements.
Predefined beans are injected with dependent scope and the predefined default qualifier @Default.
For more information about injecting resources, see Resource Injection.
The following code snippet shows how to use the @Resource annotation to inject a predefined bean. This code snippet injects a user transaction into the servlet class TransactionServlet. The user transaction is an instance of the predefined bean that implements the javax.transaction.UserTransaction interface.
import javax.annotation.Resource; import javax.servlet.http.HttpServlet; import javax.transaction.UserTransaction; ... public class TransactionServlet extends HttpServlet { @Resource UserTransaction transaction; ... }