简体   繁体   English

Spring bean,XmlWebApplicationContext中的生命周期(Web上下文)

[英]Spring beans, Lifecycle in a XmlWebApplicationContext (web context)

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. 我已经找到了关于这个问题的上一个SF问题,我相信设置init-methoddestroy-method属性就足够了。 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? 如果我理解正确,那么实现org.springframework.context.Lifecycle的类在Web应用程序上下文(即org.springframework.web.context.support.XmlWebApplicationContext )中的行为将与其他应用程序上下文中的行为不同? 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. 它将执行此操作,因为XmlWebApplicationContextstart() (将启动包含的Lifecycle bean)将在加载上下文配置文件之前执行。

Is this correct? 这个对吗?

I don't think so. 我不这么认为。 The start() method is called by doStart() and both are in AbstractApplicationContext , which is the superclass of all application contexts. start()方法由doStart()调用,两者都在AbstractApplicationContext ,后者是所有应用程序上下文的超类。 So there should be no difference. 所以应该没有区别。

The Lifecycle interface should be implemented by beans that want to participate in the container's lifecycle. Lifecycle接口应该由想要参与容器生命周期的bean实现。 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. 这主要是由容器本身实现的(参见此处的文档 ),尽管这些容器中的bean也可以在他们选择时实现它,并且启动/停止信号将传播给它们。

The start() and stop() methods are essentially notifications that the container has just started start, or is about to stop. start()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 (eg request-scope) where the bean's lifecycle is independent of the container's. 一个很好的理由是当你使用非单例范围(例如请求范围)时,bean的生命周期独立于容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM