问题描述
我有一个我希望运行的无客户端应用程序。它将没有客户端,但它将进行HTTP调用并充当其他服务的客户端。它可能运行几个小时或几天(但它不需要定期运行 - 只需一次)。
I have a no-client application that I wish to run. It will have no clients but it will make HTTP calls and act as client for other services. It would run for perhaps a few hours or days (but it will not require periodic runs -- just one-shot).
我想在Java EE中运行它7容器,因为标准的上下文依赖注入(CD)和标准的JAX-RS客户端(自Java EE 7以来的新版本)的好处。拥有JMS,JPA等服务也很不错。
I want to run it in a Java EE 7 container, because of the benefits of standard Context Dependency Injection (CD), and a standard JAX-RS client (new since Java EE 7). It is also nice to have services such as JMS, JPA.
问题是如何以标准方式编写/注释main方法?方法上的 @Inject
并不好,因为这些方法必须快速返回。 @Schedule
并不理想,因为它会定期运行,除非我以编程方式确定当前的系统时间。
The question is how do I write / annotate the main method in a standard way? @Inject
on a method is no good because such methods must return quickly. @Schedule
is not ideal because it runs periodically unless I programmatically determine current system time.
我能来的最好是在 @Inject
方法中设置一次性计时器
并使用<$ c注释我的main方法$ c> @Timeout 。
The best I could come up with is to set a one-shot Timer
in an @Inject
method and annotate my main method with @Timeout
.
不知何故,这似乎有点脆弱或不优雅。 是否有更好的标准方式来启动服务?某些注释会导致它启动并开始运行?
Somehow this seems a bit fragile or inelegant. Is there a better standard way to start the service? Some annotation that would just cause it to start and get going?
此外,如何在取消部署时中断和关闭服务的最佳标准方法是什么?
Additionally, how what is the best standard way to interrupt and shut down the service upon undeployment?
推荐答案
如果可以的话使用 EJB
使用(或代替) CDI
,然后尝试 @Singleton
+ @Startup
您的bean的注释,以及 @PostConstruct
的 main()
方法。
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();
}
}
这篇关于如何在Java EE中使用CDI编写main()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!