Search code examples
javaspringspring-web

How to add ServletContextListener to existing @Service?


I have an existing class that I want to add the ServletContextListener interface:

@Service
public class MyService {
    //...
}

@Component
public class MyController {
    @Autowired
    private MyService service;
}

This runs fine. But as soon as I add public class MyService implements ServletContextListener, then I'm getting the following error on MyController:

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private service. No qualifying bean of type [MyService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}.

The application runs on a Tomcat. My goal is to @Override public void contextDestroyed() and clean up some resources inside this specific service on tomcat shutdown.

What is wrong here?


Solution

  • Since you want to perform clean up tasks, then you should use @PreDestroy in a method in your bean:

    @Service
    public class MyService {
        @PreDestroy
        public void cleanUp() {
            //free resources...
        }
    }
    

    Spring application context will execute the clean up tasks before the bean is destroyed from the context.