Can a startup singleton bean delay a J2EE container initialization?

眉间皱痕 提交于 2019-12-13 03:46:06

问题


According to the Java EE 6 Tutorial:

The EJB container is responsible for determining when to initialize a singleton session bean instance unless the singleton session bean implementation class is annotated with the javax.ejb.Startup annotation. In this case, sometimes called eager initialization, the EJB container must initialize the singleton session bean upon application startup. The singleton session bean is initialized before the EJB container delivers client requests to any enterprise beans in the application.

My RESTEasy application served by Thorntail doesn't use any EJB, but it uses @Startup, @Singleton and @PostConstruct annotations to run a long database update task during the initialization of the application server. It is something like this:

@Startup
@Singleton
public class StartupTask {

  @PostConstruct
  void init {
    // database update task
  }
}

Will my application be able to process HTTP requests before this task completes?

My question is similar to this one.


回答1:


Any bean annotated with javax.ejb.Singleton is an EJB and subject to the conditions that you quoted in your question.

You can circumvent the delay by moving your "database update task" logic to a second EJB:

@Stateless
public class DatabaseUpdater {

    @Resource
    private Datasource dataSource;

    // OR

    @PersistenceContext
    private EntityManager em;

    @javax.ejb.Asynchronous
    public void updateDatabase() {
        // beware of long running transaction timeouts in here!
        ...
    }

}

and then call it from your @Startup bean:

@Startup
@Singleton
public class StartupTask {

    @EJB
    private DatabaseUpdater databaseUpdater;

    @PostConstruct
    void init {
        databaseUpdater.updateDatabase();
    }

}


来源:https://stackoverflow.com/questions/55894071/can-a-startup-singleton-bean-delay-a-j2ee-container-initialization

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