How to write main() using CDI in Java EE?

强颜欢笑 提交于 2019-12-08 18:21:25

If you can use the EJB with(or instead of) CDI, then try the @Singleton + @Startup annotations for your bean, and @PostConstruct for your main() method.

@Singleton
@Startup
public class YourBean {

@Stateless
public static class BeanWithMainMethod{

    @Asynchronous
    public void theMainMethod(){
        System.out.println("Async invocation");
     }
}

    @EJB
    private BeanWithMainMethod beanWithMainMethod;

    @PostConstruct
    private void launchMainMethod(){
        beanWithMainMethod.theMainMethod();
    }
}

When PostConstruct is long running, decouple with events:

@Singleton
@Startup
public class YourBean{
@Inject
private Event<XXX> started; 
@PostConstruct
private void theMainMethod(){
    started.fire(new XXX());
}
public void handleStarted(@Observes XXX started) {
    // the real main method.
}

}

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