Search code examples
javaspringear

How to rewrite ear application into Spring


I have some ear application which I need to rewrite to spring. War contains one class which run EJB:

/**
 * The ear initialization.
 */
public final class Startup extends HttpServlet {

  private static final long serialVersionUID = 6465240550145652729L;

  @EJB(name="MyStartupBean")
  private MyBeanLocal bean;

  @Override
  public void init(final ServletConfig servletConfiguration) throws ServletException {
    bean.start();
  }


  @Override
  public void destroy() {
    bean.stop();
  }
}

EJB contains some quart scheduler which run job every 30s

I really try to find some example of ear spring application with EJB but with no succes. How should I rewrite it into spring ?


Solution

  • Spring supports @EJB (not widely known but it does). So basically you can simply port your class to spring by removing the extends HttpServlet, add a @Component annotation, simplify the init method and add @PostConstruct and add @PreDestroy to the destroy method.

    @Component
    public final class Startup {
    
      private static final long serialVersionUID = 6465240550145652729L;
    
      @EJB(name="MyStartupBean")
      private MyBeanLocal bean;
    
      @PostConstruct
      public void init() {
        bean.start();
      }
    
      @PreDestroy
      public void destroy() {
        bean.stop();
      }
    }
    

    Something like that would be the result. Now either declare this bean in xml

    <bean class="Startup" />
    

    Or use component scanning to detect/pickup this bean.

    But as mentioned I would probably ditch the EJB altogether and use spring to bootstrap Quartz instead.