问题
Is there any bean type or Java EE annotation to get a bean initialized at container startup without adding the bean to beans.xml?
回答1:
Yes, there is.
This is what I use when I need a singleton, application scoped bean started on deploy:
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.annotation.PostConstruct;
@Named( "myBean" )
@ApplicationScoped
@Startup
@Singleton
public class MyBean {
@PostConstruct
public void postConstruct() {}
}
The postConstruct
method is added if you need any code to be executed besides initialization.
回答2:
You can use a Singleton
bean as shown in Initializing Singleton Session Beans:
import javax.ejb.Singleton;
import javax.ejb.Startup;
@Startup
@Singleton
public class StartupBean {
}
来源:https://stackoverflow.com/questions/46750356/java-ee-7-containers-initialize-bean-at-startup-without-adding-it-to-beans-xml