В Spring/|InitializingBean и DisposableBean являются двумя интерфейсами маркеров, полезными для Spring для выполнения определенных действий при инициализации и уничтожении компонентов.
- Для компонента, реализованного с помощью InitializingBean, он будет запущен
afterPropertiesSet()
после того, как все свойства компонента будут установлены. - Для боба, реализованного DisposableBean, он будет запущен
destroy()
после того, как контейнер Spring освободит боб.
Пример
Вот пример, чтобы показать вам, как использовать InitializingBean и Одноразовый/|. Компонент обслуживания клиентов для реализации интерфейса InitializingBean и DisposableBean и имеет свойство message.
package com.mkyong.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.mkyong.common; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mkyong.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(); } }
Конфигурируемый ApplicationContext.close() закроет контекст приложения, освободив все ресурсы и уничтожив все кэшированные одноэлементные компоненты. Он используется только для уничтожения()
демонстрационной цели метода 🙂
Выход
Init method after properties are set : im property message com.mkyong.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() вызывается после установки свойства message; в то время как метод destroy() вызывается после context.close();
Скачать Исходный Код
Рекомендации
Оригинал: “https://mkyong.com/spring/spring-initializingbean-and-disposablebean-example/”