简体   繁体   中英

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.

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 . Is the singleton condition respected by CDI in this case, or it will create a @New instance of MyCacheRepository whenever it is required?

Also according to the documentation, "Beans with scope @Singleton don't have a proxy object. Clients hold a direct reference to the singleton instance." 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.

You could also just add a @PostConstruct method to your @Singleton and see if it's called twice.

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."

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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