天天看点

java destory_关于java:Spring bean destroy方法

什么可能是在现实世界的应用程序中使用destroy方法的示例? 为什么正在运行的应用程序想要销毁它的bean? 如果bean是由用于Web应用程序的spring容器创建的,例如ContextLoaderListener,那么如何重新创建这些bean,因为容器已经启动。 有没有办法重新启动弹簧IoC容器而无需重新启动应用程序服务器?

一个例子是DataSource或任何需要清理的资源。你可能会有这样的事情:

@Bean(destroyMethod ="close")

DataSource dataSource() {

....

}

这在具有多个类加载器的环境中尤其重要,例如应用程序服务器以防止内存泄漏。

有时候这样做是多余的,因为底层资源可以自己进行清理(比如作为servlet生命周期中contextDestroyed事件的一部分),但是你应该总是验证这一点。

这些春季文档也是一个有用的参考。引用的例子类似:

那么bean类:

public class ExampleBean {

public void cleanup() {

// do some destruction work (like releasing pooled connections)

}

}

可以刷新上下文。这个答案提供了一个很好的解释,当你可能想要这样做。

吼叫是我的看法:

What could be a possible example use of destroy method in a real world application?

对于大多数应用程序,我们可能主要关注实际业务,因此我们不会经常遇到需要定义destroy方法的场景。但是当你遇到一些基本组件或中间件时,你需要注意资源管理,例如数据库连接,内存使用,磁盘使用等。你必须知道如何清楚地释放不必要的资源,或者这将导致严重的问题。

If the beans are created by the spring container for the web application by, say, ContextLoaderListener, then how can these beans be recreated, because the container already started?

Spring Container不仅适用于Web应用程序,它还可以服务于常见的Java应用程序(Main Application)。 Spring Container有两种不同的Bean Type(Singleton和Prototype),Single Spring Bean只在Spring Container启动时预先实例化,而Prototype Bean每次都会通过调用getBean来实例化。

Is there a way to restart the spring IoC container without restarting the Application server?

Spring IoC Container开始通过调用AbstractRefreshableApplicationContext.refresh()方法进行实例化。如果您之前已实例化Container,则此方法将销毁整个Spring IoC Container。因此,您可以调用此方法来重新实例化Container。如果你想了解Spring IoC Mechanism,我建议你阅读Spring的源代码:spring-core,spring-beans,spring-context。

希望能帮到你。

我在Spring应用程序中看到了直接或间接启动非守护程序线程的bean。然后就不可能在不杀死进程的情况下停止进程。这影响了一些处理自动化测试的Jenkins工作。所以在DevOps世界中有很多真实世界的例子