Пример Spring InitializingBean и DisposableBean
В SpringInitializingBean иDisposableBean - это два интерфейса маркеров, удобный способ для Spring выполнять определенные действия при инициализации и уничтожении bean-компонента.
-
Для реализованного компонента InitializingBean он будет запускать
afterPropertiesSet()после того, как будут установлены все свойства компонента. -
Для bean-компонента DisposableBean он будет запускать
destroy()после того, как контейнер Spring освободит bean-компонент.
пример
Вот пример, показывающий вам, как использоватьInitializingBeanandDisposableBean. Bean-компонент CustomerService для реализации интерфейса InitializingBean и DisposableBean и имеет свойство сообщения.
package com.example.customer.services;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class CustomerService implements InitializingBean, DisposableBean
{
String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void afterPropertiesSet() throws Exception {
System.out.println("Init method after properties are set : " + message);
}
public void destroy() throws Exception {
System.out.println("Spring Container is destroy! Customer clean up");
}
}
Файл: Spring-Customer.xml
Запустить его
package com.example.common;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.customer.services.CustomerService;
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
CustomerService cust = (CustomerService)context.getBean("customerService");
System.out.println(cust);
context.close();
}
}
ConfigurableApplicationContext.close() закроет контекст приложения, освободив все ресурсы и уничтожив все кэшированные одноэлементные bean-компоненты. Используется только для демонстрации методаdestroy() :)
Выход
Init method after properties are set : im property message com.example.customer.services.CustomerService@47393f ... INFO: Destroying singletons in org.springframework.beans.factory. support.DefaultListableBeanFactory@77158a: defining beans [customerService]; root of factory hierarchy Spring Container is destroy! Customer clean up
Метод afterPropertiesSet () вызывается после установки свойства сообщения; в то время как метод destroy () вызывается после context.close ();
Thoughts…
Я бы не рекомендовал использовать интерфейс InitializingBean и DisposableBean, потому что он будет тесно связывать ваш код с Spring. Лучше всего указать атрибутыinit-method and destroy-method в файле конфигурации вашего компонента.