如何使用@Inject 注释在 Java 中堆叠自定义注释 [英] How to stack custom annotation in Java with @Inject annotation
问题描述
我在浏览时多次看到这个..人们使用 @Inject
注释和他们自己的注入 EntityManager
像这样:
I saw this several times when browsing.. people are using @Inject
annotation with their own to inject EntityManager
like this:
@Inject @MyEm EnityManager em;
因为你不能只注入 EntityManager
.您只能使用 @PersistenceContext
来完成.有没有人知道如何使这项工作(使用自定义注释),因为我没有在网上找到任何信息?如果可以,请举个例子.
because you cannot just inject the EntityManager
. You can do it only with @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.
推荐答案
基本上,您需要做的是创建一个鉴别器注释并将其与 Producer 结合使用.这允许您在 Java EE 应用程序中的其他 bean 中简单地 @Inject 实体管理器.下面是一个例子:
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. 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;
}
这篇关于如何使用@Inject 注释在 Java 中堆叠自定义注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!