Search code examples
javadesign-patternsservlet-listeners

Design for running of Service during Server startup in Java


I want to start a service which starts along with Server and never ends until server is killed. So first I have gone with ServletContextListner class where I implemented my logical part to run the method using

while(true){ 
    try{ // do the jobs } 
    catch(Exception e){} 
}

But then i felt it's not good to implement this job at Listener class. Then I moved to one ServiceManager class and doing the same job, but gives me an edge in injecting properties using Spring which is not possible in Listener class.

But fundamental question on how better/from where can I invoke this class and call the startService method which runs infinitly.

public void contextInitialized(ServletContextEvent event) {
        logger.info(" *** START MyListener ****");
        context = event.getServletContext();
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        MyServiceManager serviceManager = (MyServiceManager) ctx.getBean("myServiceManager");
        serviceManager.startService();
        logger.info(" *** END MyListener ****");
    }

or any idea how to invoke/implement such service to run in server forever without any abstractions [under any case, this shouldn't be killed unless server is stopped]


Solution

  • This is a duplicate question see: Background process in Servlet

    So you can do what is explained in that answer and if you need to then load your Spring configured beans using applicationContext.getBean("yourBean");