1

Consider this example

@Component
class MyExpensiveClass {
  private DB db;
}

When Spring application instantiates, a bean myExpensiveClass is created.

Now if I am shutting down the applicationContext, I would like to release the handle to db.

Is there a way I can do that in Spring? like implementing a method and Spring calls it?

daydreamer
  • 87,243
  • 191
  • 450
  • 722

1 Answers1

0

If you are using xml configuration, you can register an init and destroy method

<bean id="customerService"class="com.mkyong.customer.services.CustomerService" 
          init-method="initIt" destroy-method="cleanUp">

If you are using annotations only

@Configuration
public class AppConfig {
    @Bean(initMethodName="init")
    public Foo foo() {
        return new Foo();
    }
    @Bean(destroyMethodName="cleanup")
    public Bar bar() {
        return new Bar();
    }
}

Documentation

Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136