Question

I have a Java SE application with CDI/Weld (started with org.jboss.weld.environment.se.StartMain).

I'm injecting a @Singleton bean into another bean:

public class CdiMain {

    @Inject
    private MySingleton mySingleton;

    public void onStart(@Observes ContainerInitialized event) {
        mySingleton.printHello();
        mySingleton = null;

        // other long running stuff
    }
}

I don't need the singleton bean after the printHello method. When will it be destroyed?

Was it helpful?

Solution

From the docs it is unclear if a @Singleton bean will be destroyed at some specific point.
I wouldn't rely on that. For instance during Weld.shutdown() @PreDestroy method is not called on a @Singleton.

Use @ApplicationScoped bean instead, it's functionally the same (except that it's proxied), also available in Java SE and will be 'destroyed' when the application context ends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top