春天的核心.默认的@Bean destroy方法

Ser*_*gii 16 java spring release

我有自己的豆子:

@Bean
public MyBean myBean(){...
Run Code Online (Sandbox Code Playgroud)

按照spring文档发布自己应该指定的资源destroyMethod.如果destroyMethod没有直接指定,我没有找到弹簧调用的任何默认destroy方法.

我用了

@Bean(destroyMethod = "close")
public MyBean myBean(){...
Run Code Online (Sandbox Code Playgroud)

但是如果它默认具有值,可以考虑不直接指定destroy方法.


默认情况下,像春天在什么试一下destroy,close,release?如果spring默认尝试一些方法来释放资源 - 哪些?

Mar*_*eel 31

作为记录在Bean.destroyMethod:

为方便用户,容器将尝试针对从该@Bean方法返回的对象推断出destroy 方法.例如,给定一个@Bean返回Apache Commons DBCP BasicDataSourceclose()方法,容器将注意到该对象上可用的方法并自动将其注册为 destroyMethod.这种"破坏方法推理"目前仅限于检测名为"close"或"shutdown"的公共,非arg方法.

换句话说,如果您没有指定destroyMethod,但bean有public close()shutdown()method,它将自动用作destroy-method.

要禁用此推断,请使用@Bean(destroyMethod = "").


kk.*_*kk. 8

您可以实现一个方法,该方法将在销毁之前执行并使用它进行注释 @PreDestroy

@PreDestroy
public void methodName() {
    //Your code..
}
Run Code Online (Sandbox Code Playgroud)


小智 7

org.springframework.beans.factory.DisposableBean接口指定一个方法 -

void destroy() throws Exception;
Run Code Online (Sandbox Code Playgroud)

简单地实现它 -

public class ExampleBean implements DisposableBean {
   public void destroy() {
      // do some destruction work
   }
}
Run Code Online (Sandbox Code Playgroud)

用于基于XML的配置

<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>
Run Code Online (Sandbox Code Playgroud)

在豆子里

public class ExampleBean {
   public void destroy() {
      // do some destruction work
   }
}
Run Code Online (Sandbox Code Playgroud)

或使用@PreDestroy注释