版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37606901/article/details/82532797
可以为 Bean 定制初始化后的生命行为,也可以为 Bean 定制销毁前的生命行为。废话不多说直接上菜:
package com.bjpowernode.ba06;
public interface ISomeService {
void doSome();
}
package com.bjpowernode.ba06;
public class SomeServiceImpl implements ISomeService {
public SomeServiceImpl() {
System.out.println("执行无参构造器");
}
@Override
public void doSome() {
System.out.println("执行doSome()方法");
}
public void setUp() {
System.out.println("生命起始");
}
public void tearDown() {
System.out.println("销毁之前");
}
}
<?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">
<!-- 注册Service -->
<bean id="myService" class="com.bjpowernode.ba06.SomeServiceImpl"
init-method="setUp" destroy-method="tearDown"/>
</beans>
package com.bjpowernode.ba06;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
// 创建容器对象,加载Spring配置文件
String resource = "com/bjpowernode/ba06/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
// 对于销毁方法的执行,有两个条件:
// 1)当前的Bean需要是singleton的
// 2)要手工关闭容器
((ClassPathXmlApplicationContext)ac).close();
}
}
执行的结果为:
执行无参构造器
生命起始
执行doSome()方法
销毁之前