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

I have a clientless application that I want to run. He will not have clients, but he will make HTTP calls and act as a client for other services. It will probably work for several hours or days (but it will not require periodic runs - just one shot).

I want to run it in a Java EE 7 container due to the advantages of the standard Injection Context Dependency Injection (CD) and the standard JAX-RS client (new with Java EE 7). It is also nice to have services such as JMS, JPA.

The question is, how can I write / annotate the main method in a standard way? @Inject for a method is not good, because such methods should return quickly. @Schedule not ideal as it runs periodically unless I programmatically determine the current system time.

The best I could come up with was to set a one-time Timer in the @Inject method and annotate my main method with @Timeout .

Somehow it seems a little fragile or inelegant. Is there a better standard way to start a service? Some annotation that just starts it and starts?

Also, what is the best standard way to interrupt and disable a service during deployment ?

+1
source share
2 answers

If you can use EJB with (or instead of) CDI , try @Singleton + @Startup annotations for 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(); } } 
+2
source

When PostConstruct is running for a long time, discard the 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. } 

}

+3
source

Source: https://habr.com/ru/post/1480050/


All Articles