3

If i write a simple servlet application, in my servlet class i extend the http servlet. This lets the container know that my class is a servlet and it will manage the 'lifecycle' of the servlet. init, doget(), destroy() etc.

But the Spring MVC framweork controller class does not extend any servlet class. it is jsut a POJO with it s own custom methods. Now I can call those methods individually using Requestmapping.

But will this spring controller class be 'mananged' by the container in a same way a servlet lifecyle is managed?

Victor
  • 16,609
  • 71
  • 229
  • 409

1 Answers1

3

But will this spring controller class be 'mananged' by the container in a same way a servlet lifecyle is managed?

Not directly. Then entry point of a Spring MVC application is typically a DispatcherServlet*. This class extends (not directly, but through inheritance) HttpServlet. You declare it as you would any other Servlet, typically in web.xml.

However you don't declare it by itself. You provide a Spring ApplicationContext from which the DispatcherServlet can go and get the @Controller annotated classes it will use to handle requests.

The DispatcherServlet handler stack is pretty big. There are many components involved. The official Spring MVC is an excellent document. You should read it.

*I say typically because Spring provides other handlers, HttpRequestHandler for example.


Additional Reading:

  1. Spring MVC and Servlets 3.0 - Do you still need web.xml?
  2. What happens behind the scenes of deploying a Spring MVC application to tomcat outside of eclipse?
  3. What's the difference between @Component, @Repository & @Service annotations in Spring?
  4. Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?
  5. Difference between <context:annotation-config> vs <context:component-scan>
  6. ContextLoadListener and DispatcherServlet
Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Thanks. But the individual controllers still follow a lifecycle? – Victor Oct 08 '13 at 00:59
  • @KaushikGuha The controllers are spring managed beans. Their lifecycle is tied to that of the `ApplicationContext` to which they belong. That is usually tied to the lifecyle of the `DispatcherServlet` which depends on the container. – Sotirios Delimanolis Oct 08 '13 at 00:59
  • in a traditional servlet i can write initialisation code and cleanup code in the init() and destroy() method. In a spring managed bean, is there a way to do it? Thank you – Victor Oct 08 '13 at 02:28
  • @KaushikGuha Yes, if you go in the chapter 5 of the Spring documentation, you can declare `init` and `destroy` type methods for your bean classes. When the `ApplicationContext` is closed or destroyed, the `destroy` method will get called for any bean declaring it. The `init` method (not necessarily by that name, but there are rules) will be called with the bean is created. – Sotirios Delimanolis Oct 08 '13 at 02:30