在另一个示例中,如何在Spring中初始化和销毁bean?您将看到如何使用Spring配置init-method和初始化和销毁Bean destroy-method。
在以下示例中,您将看到如何使用Spring API实现相同的功能。在这种情况下,我们的类需要实现InitializingBean和DisposableBean。这些接口位于org.springframework.beans.factory包装下。
该InitializingBean接口要求我们实现该afterPropertiesSet()方法。该方法将成为我们bean的init方法。在destroy()这是在定义的合同法DisposableBean界面,我们会在把我们的bean的清理逻辑。
使用这种方法的缺点是我们的类必须使用Spring API。如果您想使用上述其他方法在Spring容器之外使用类,则是更好的方法。
现在,让我们来看一些实际的代码。
package org.nhooo.example.spring.destroy; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; public class InitDisposeService implements InitializingBean, DisposableBean { /** * Do some processes. */ public void doSomething() { System.out.println("InitDisposeService.doSomething"); } /** * Initialize bean after property set. * * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { System.out.println("InitDisposeService.afterPropertiesSet"); } /** * Clean-up bean when the context is closed. * * @throws Exception */ @Override public void destroy() throws Exception { System.out.println("InitDisposeService.destroy"); } }
与往常一样,我们定义Spring配置(init-dispose.xml)来注册我们的bean。在这种情况下,我们将创建一个ID为的bean,service并将使用InitDisposeService该类。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="service"/> </beans>
下面是一个小的Java程序,可用于运行我们的应用程序。这将加载Spring配置,从容器中获取bean并执行bean。我们将看到该afterPropertiesSet方法被调用。当上下文关闭时,该destroy方法也将执行。
package org.nhooo.example.spring.destroy; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InitDisposeDemo { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("init-dispose.xml"); InitDisposeService service = (InitDisposeService) context.getBean("service"); service.doSomething(); context.close(); } }
这是屏幕上显示的输出:
InitDisposeService.afterPropertiesSet InitDisposeService.doSomething InitDisposeService.destroy