How to stack custom annotation in Java with @Inject annotation

吃可爱长大的小学妹 提交于 2019-12-12 10:02:25

问题


I saw this several times when browsing.. people are using @Inject annotation with their own to inject EntityManager like this:

@Inject @MyEm EnityManager em;  

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.


回答1:


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;
}



回答2:


This is called a "qualifier". Every CDI tutorial should explain about them. In short:

  • create your own annotation, and annotate it with @Qualifier
  • use your qualifier annotation on your concrete classes that implement some interface, or on producer methods that create an instance
  • use your custom annotation at the injection point to differentiate between two or more implementations of an interface


来源:https://stackoverflow.com/questions/8770465/how-to-stack-custom-annotation-in-java-with-inject-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!