简体   繁体   English

CDI @New on @Singleton对象。 它能做什么?

[英]CDI @New on @Singleton objects. What it does?

I'm trying to define a CDI producer to inject one or another instance of an object. 我正在尝试定义CDI生产者以注入对象的一个​​或另一个实例。

Here's the code of the producer: 这是生产者的代码:

@Produces
public static MyRepository getMyRepository(@New MyCacheRepository cache, 
                                                                @New MyNormalRepository db) {

    if(conditions) {
        return cache;
    }

    return db;

}

MyCacheRepository is declared as @javax.inject.Singleton . MyCacheRepository声明为@javax.inject.Singleton Is the singleton condition respected by CDI in this case, or it will create a @New instance of MyCacheRepository whenever it is required? 是CDI在这种情况下,推崇单身状态,或者它会创建一个@New的实例MyCacheRepository当需要它?

Also according to the documentation, "Beans with scope @Singleton don't have a proxy object. Clients hold a direct reference to the singleton instance." 同样根据文档,“具有作用域@Singleton的Bean没有代理对象。客户端直接引用单例实例。” Knowing this, you should be able to find the answer for yourself by checking the injected object's identity and compare it to where you don't use @New. 知道这一点,您应该能够通过检查注入的对象的身份并将其与不使用@New的位置进行比较来为自己找到答案。

You could also just add a @PostConstruct method to your @Singleton and see if it's called twice. 您也可以只将@PostConstruct方法添加到@Singleton中,看看它是否被调用过两次。

As an aside, the documentation warns that @New is deprecated: "The @New qualifier was deprecated in CDI 1.1. CDI applications are encouraged to inject @Dependent scoped beans instead." 顺便说一句,文档警告@New已被弃用:“ @New限定符在CDI 1.1中已弃用。鼓励CDI应用程序注入@Dependent范围内的bean。”

See also: 也可以看看:

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

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