javajakarta-eecdiweldjboss-weld

How to make a singleton in CDI 1.2


I use weld 2.3.5 which supports CDI 1.2. I came across a problem that CDI beans, annotated with @javax.inject.Singleton are ignored by the container (bean-discovery-mode="annotated").

After googling I still can't find information about singletons and CDI 1.2. Could anyone explain the situation and give example how to make singleton CDI bean with CDI 1.2.


Solution

  • With bean discovery mode annotated, CDI will only pick up bean annotated with so-called bean defining annotations. The spec clearly defines these and as you might expect, @Singleton is not amongst them.

    To make your singleton recognizable, easiest way would be to just use discovery mode all but I suppose you want to avoid that. In which case perhaps an extension could be used to register the annotated type of your singleton - CDI should be able to pick up from there.

    Then again, the usage of CDI @Singleton is very limited/specific as it is a non-proxy pseudo-scope. In most cases, @ApplicationScoped will do exactly what you want anyway so make sure you consider that before doing any extra work.