Nicola Ferraro
Nicola Ferraro

Reputation: 4189

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?

Upvotes: 1

Views: 418

Answers (1)

user201891
user201891

Reputation:

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:

Upvotes: 2

Related Questions