Spring init-метод и пример метода разрушения
В Spring вы можете использоватьinit-method иdestroy-method в качестве атрибутов в файле конфигурации bean-компонента для выполнения определенных действий при инициализации и уничтожении. АльтернативаInitializingBean and DisposableBean interface.
пример
Вот пример, чтобы показать вам, как использоватьinit-method иdestroy-method.
package com.example.customer.services; public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void initIt() throws Exception { System.out.println("Init method after properties are set : " + message); } public void cleanUp() throws Exception { System.out.println("Spring Container is destroy! Customer clean up"); } }
File : Spring-Customer.xml, определите атрибутыinit-method иdestroy-method в вашем bean-компоненте.
Запустить его
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 закроет контекст приложения, освободив все ресурсы и уничтожив все кэшированные одноэлементные компоненты.
_
Output_
Init method after properties are set : i'm 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
МетодinitIt() вызывается после установки свойства сообщения, а методcleanUp() вызывается после context.close ();
Thoughts…
Всегда рекомендуется использоватьinit-method иdestroy-method в файле конфигурации bean вместо реализации интерфейсов InitializingBean и DisposableBean, чтобы излишне связывать ваш код с Spring.