jhyot
jhyot

Reputation: 3955

Prevent manual instantiation of @ApplicationScoped CDI managed bean

I have a Singleton class in my Java EE application. I'm achieving this by annotating the class with @ApplicationScoped and letting CDI handle everything.

My question is whether I can prevent accidental manual instantiation of this class, since CDI requires that I have a non-private no-argument constructor?

The "classic" non-CDI solution would have a private constructor, a static INSTANCE field and a static factory method that returns this instance.

Upvotes: 1

Views: 278

Answers (1)

Brett Kail
Brett Kail

Reputation: 33936

You can use the "classic" non-CDI solution you mention, and then annotate the factory method (or static final field) with @Produces.

Upvotes: 3

Related Questions