Skip to content

spring lifecycle

Eric F. Alsheimer edited this page Jan 12, 2018 · 1 revision

Spring Lifecycle

Simple Spring Lifecycle

  • The request originates from the client - the browser. The browser is maybe asking for "localhost:8080/"
  • The container (SpringApplication) loads the DispatcherServlet because web.xml:: is 1.
  • DispatcherServlet intercepts the request and examines URI pattern as provided in web.xml::.
  • DispatcherServlet finds action with @RequestMapping of "/" in, say, WelcomeController#doWelcome()
  • doWelcome() constructs the model or data called, say, welcomeMessage and uses a service welcomeService wired from bean injection after reading the bean declaration in the springMvcDemo-servlet.xml
  • WelcomeController returns a view name "welcomeNew" which is resolved in the InternalResourceViewResolver (also declared in the springMvcDemo-servlet.xml, along with a prefix and suffix).
  • InternalResourceViewResolver calls RequestDispatcher to forward the request to the resolved view welcomeNew.jsp
  • welcomeNew.jsp renders the model along with its own processing.

Spring Lifecycle Callbacks

Beans can be told to expose access to their lifecycle hooks, such as creation or destruction, by including interfaces.

  • interface InitializingBean#afterPropertiesSet() - on initialization of a bean after the properties are set
  • interface disposableBean#destroy() - on destruction of a singleton

You can also link into these hooks by adding

Initialization Order

When beans are created, the constructor is executed (if Constructor-based injection is enabled) and then setters are called (if Setter-based injection is enabled), then init method is invoked.

You can wire up the init and destroy callbacks using the .xml file that declares your beans, using Eclipse, by putting the method names in the init and destroy fields.

Constructor is performed before initialization callback is called, and destroy is called before the bean is destroyed.

In nested beans, the higher-level beans that use lower-level beans will call their constructor callbacks first. That should just make sense since their constructors will be instantiating the lower-level beans. The higher-level will also call their destructors first as well, for the same reason.

Clone this wiki locally