简体   繁体   English

如何使用@Inject注释在Java中堆叠自定义注释

[英]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: 简而言之:

  • create your own annotation, and annotate it with @Qualifier 创建自己的注释,并使用@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 在注入点使用自定义批注来区分接口的两个或更多个实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM