1

我有一个希望运行的无客户端应用程序。它没有客户端,但会进行 HTTP 调用并充当其他服务的客户端。它可能会运行几个小时或几天(但它不需要定期运行——只需一次)。

我想在 Java EE 7 容器中运行它,因为标准上下文依赖注入 (CD) 和标准 JAX-RS 客户端(Java EE 7 以来的新客户端)的好处。拥有 JMS、JPA 等服务也很不错。

问题是我如何以标准方式编写/注释主要方法?@Injecton 一个方法是不好的,因为这样的方法必须快速返回。@Schedule并不理想,因为它会定期运行,除非我以编程方式确定当前系统时间。

我能想出的最好办法是Timer@Inject方法中设置一个单一镜头,并用@Timeout.

不知何故,这似乎有点脆弱或不雅。是否有更好的标准方式来启动服务?一些只会导致它启动并开始运行的注释?

此外,在取消部署时中断和关闭服务的最佳标准方法是什么

4

2 回答 2

3

当 PostConstruct 长时间运行时,与事件解耦:

@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.
}

}

于 2013-05-11T21:10:37.790 回答
2

如果您可以使用EJBwith(or instead of) CDI,请尝试为您的 bean 和您的方法使用@Singleton+注释。@Startup@PostConstructmain()

@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();
    }
}
于 2013-05-11T18:04:08.147 回答