Spring bean初始化和销毁某些动作(十)

1.实现InitializingBean,DisposableBean接口,覆写方法

具体实现如下:

public class SetByJava implements InitializingBean,DisposableBean{

	public void destroy() throws Exception {
		System.out.println("destroy");
		
	}

	public void afterPropertiesSet() throws Exception {
		System.out.println("init");
	}

	public void doSomething() {
		System.out.println("doSomething");
	}
}

配置bean

	<bean id="text" class="InitAndDestroy.SetByJava">
	</bean>

测试,实例化ConfigurableApplicationContext,调用其close方法模拟销毁。

		ConfigurableApplicationContext app = new ClassPathXmlApplicationContext("initText.xml");
		SetByJava demo = (SetByJava)app.getBean("text");
		demo.doSomething();
		app.close();

测试结果:
在这里插入图片描述
2.配置bean的时候指明初始跟销毁方法

如下:

public class SetByXml{
	public void destroy() throws Exception {
		System.out.println("destroy");	
	}
	public void afterPropertiesSet() throws Exception {
		System.out.println("init");
	}
	public void doSomething() {
		System.out.println("doSomething");
	}
}

配置bean:

<bean id="text2" class="InitAndDestroy.SetByXml" init-method="afterPropertiesSet" destroy-method="destroy">
</bean>

测试可得到同样的结果。

3、基于注解的配置

如下:

public class SetByAnno{
	@PreDestroy
	public void destroy() throws Exception {
		System.out.println("destroy");	
	}
	@PostConstruct
	public void afterPropertiesSet() throws Exception {
		System.out.println("init");
	}
	public void doSomething() {
		System.out.println("doSomething");
	}
}

配置bean:

<context:annotation-config />
<bean id="text3" class="InitAndDestroy.SetByAnno">
</bean>

测试可得到同样的结果。

猜你喜欢

转载自blog.csdn.net/qq_36831305/article/details/88897661