1. Defining a resource CDI规范使用术语资源是指,一般地,以下列任何一种类型的对象,在Java EE组件环境可能是可用的:
JDBC Datasources, JMS Queues, Topics and ConnectionFactorys, JavaMail Sessions and other transactional resources including JCA connectors,
JPA EntityManagers and EntityManagerFactorys,
remote EJBs, and
web services. 我们通过标注一个生产者(Producer)组件环境声明一个资源,比如
@Resource , @EJB, @PersistenceContext, @PersistenceUnit or @WebServiceRef.
@Produces
@WebServiceRef(lookup="java:app/service/Catalog")
Catalog catalog;
@Produces
@Resource(lookup="java:global/env/jdbc/CustomerDatasource")
@CustomerDatabase
Datasource customerDatabase;
@Produces
@PersistenceContext(unitName="CustomerDatabase")
@CustomerDatabase
EntityManager customerDatabasePersistenceContext;
@Produces
@PersistenceUnit(unitName="CustomerDatabase")
@CustomerDatabase
EntityManagerFactory customerDatabasePersistenceUnit;
@Produces
@EJB(ejbLink="../their.jar#PaymentService")
PaymentService paymentService;
字段可以是静态的(但不是Final的)。 一个资源声明需要包含两部分信息:
EJB link,JNDI名称,持久性单元名称(JPA persistence unit name),或其他元数据需要从组件环境获取一个资源
将使用的类型和限定符注入到我们的引用bean。
2.Typesafe resource injection 这些资源可以按照常规的方式注入。
@Inject Catalog catalog;
@Inject @CustomerDatabase Datasource customerDatabase;
@Inject @CustomerDatabase EntityManager customerDatabaseEntityManager;
@Inject @CustomerDatabase EntityManagerFactory customerDatabaseEntityManagerFactory;
@Inject PaymentService paymentService;
资源的bean类型和限定符是由Producer字段声明。看起来你可能觉得这是不必要的额外操作,只是为了获得一个额外的间接层。 你可以直接使用组件环境注入,对吗?但请记住,你使用EntityManager等资源在几个不同的bean,需要更多类型安全的写入方式.