问题描述
我浏览..人都在用 @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.
推荐答案
基本上你需要做的是建立一个鉴别注释和结合生产者使用方法。这使您可以在您的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;
}
这篇关于如何堆叠在Java中的自定义批注与@Inject注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!