Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring beans, Lifecycle in a XmlWebApplicationContext (web context)

Tags:

java

spring

I have already found a previous SF question regarding this issue and I believe setting the init-method and the destroy-method properties will be sufficient. But I wanted to hopefully ask the question a different way to further my understanding.

If I understand things correctly, a class that implements org.springframework.context.Lifecycle will behave different in a web app context (namely org.springframework.web.context.support.XmlWebApplicationContext) than in other application contexts? It will do this because the start() of the XmlWebApplicationContext (which will start the contained Lifecycle beans) will have been performed before the context configuration files are loaded.

Is this correct?

like image 219
Matt Avatar asked Dec 31 '25 00:12

Matt


1 Answers

The Lifecycle interface should be implemented by beans that want to participate in the container's lifecycle. This is primarily intended to be implemented by the containers themselves (see docs here), although beans inside those containers can implement it also if they choose, and the start/stop signals will be propagated to them.

The start() and stop() methods are essentially notifications that the container has just started start, or is about to stop.

I'm struggling to find a good use case for this, for application components. Business objects should only be concerned with their own lifecycle, rather than with the container's lifecycle. One good reason why is when you use non-singleton scopes (e.g. request-scope) where the bean's lifecycle is independent of the container's.

like image 128
skaffman Avatar answered Jan 01 '26 14:01

skaffman