Java EE 7 containers: initialize bean at startup without adding it to beans.xml?

一世执手 提交于 2019-12-24 20:01:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!