[英]How to stack custom annotation in Java with @Inject annotation
I saw this several times when browsing.. people are using @Inject
annotation with their own to inject EntityManager
like this: 我在浏览时多次看到此内容。人们使用@Inject
注释自己注入EntityManager
如下所示:
@Inject @MyEm EnityManager em;
because you cannot just inject the EntityManager
. 因为您不能只注入EntityManager
。 You can do it only with @PersistenceContext
. 您只能使用@PersistenceContext
做到这一点。 Does anybody know how to make this work (with the custom annotation), because I didn't find any information on the net? 有人知道我如何在网上找不到任何信息,该怎么做(使用自定义注释)呢? Give a example if you can, please. 请举一个例子。
Basically what you need to do is create a discriminator annotation and use it in conjunction with a Producer. 基本上,您需要做的是创建一个鉴别符注释,并将其与生产者结合使用。 This allows you to simple @Inject your Entity Manager in other beans within your Java EE application. 这使您可以在Java EE应用程序内的其他bean中简单地@Inject实体管理器。 Here is an example: 这是一个例子:
@Qualifier
@Retention(RUNTIME)
@Target(METHOD, FIELD, PARAMETER, TYPE)
public interface @MyEm {
}
public class EntityProducer {
@PersistenceContext(unitName = 'MyPU', type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
@Produces
@MyEm
public EntityManager getEntityManager() {
return entityManager;
}
}
public class MyDAO {
@Inject
@MyEm
private EntityManager entityManager;
}
This is called a "qualifier". 这称为“限定符”。 Every CDI tutorial should explain about them. 每个CDI教程都应对此进行解释。 In short: 简而言之:
@Qualifier
创建自己的注释,并使用@Qualifier
对其进行注释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.