Spring可以通过配置init-method和destroy-method属性来在容器生成和销毁时分别执行一段代码,但在我的demo中,作为init方法的start方法执行了,而作为destroy方法的shutdown方法一直没有执行,代码如下:
配置文件:
<?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 class="com.ljh.beans.Foo2" id="foo2" scope="prototype" init-method="start" destroy-method="shutdown">
<property name="foo" ref="foo"></property>
</bean>
<bean class="com.ljh.beans.Foo" id="foo" scope="prototype">
<property name="num" value="2"></property>
</bean>
</beans>
Bean文件:
public class Foo2 {
private Foo foo;
public void say(){
System.out.println("Foo2 method:" + foo.hashCode());
System.out.println("Foo2 hashcode" + this.hashCode());
System.out.println("----------------------");
}
private void start() {
System.out.println("Start method");
}
private void shutdown() {
System.out.println("Shutdown method");
}
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
}
测试方法:
public class Test01 {
private ApplicationContext context;
@Before
public void init() {
context = new ClassPathXmlApplicationContext("/springConfig.xml");
}
@Test
public void Test() {
Foo2 foo2 = (Foo2) context.getBean("foo2");
System.out.println(foo2.getFoo().getNum());
}
@After
public void After() {
System.out.println("In after method");
((ClassPathXmlApplicationContext) context).close();
}