通过在bean中设置init-method和destroy-method
配置bean
spring-lifecycle.xml1
2
3
4
5
6
<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="beanLifeCycle" class="com.sh.imcdemo.services.impl.BeanLifeCycle" init-method="start" destroy-method="stop"></bean>
</beans>com.sh.imcdemo.services.impl 实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.sh.imcdemo.services.impl;
/**
* Created by Mr SJL on 2016/11/26.
*
* @Author Junlan Shuai
*/
public class BeanLifeCycle
{
public void start()
{
System.out.println("Bean start.");
}
public void stop()
{
System.out.println("Bean stop.");
}
}
通过实现InitializingBean和DisposableBean接口
配置bean
spring-lifecycle.xml1
2
3
4
5
6
<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="beanLifeCycle1" class="com.sh.imcdemo.services.impl.BeanLifeCycle"></bean>
</beans>com.sh.imcdemo.services.impl实现类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package com.sh.imcdemo.services.impl;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Created by Mr SJL on 2016/11/26.
*
* @Author Junlan Shuai
*/
public class BeanLifeCycle implements InitializingBean, DisposableBean
{
public void destroy() throws Exception
{
System.out.println("Bean destory.");
}
public void afterPropertiesSet() throws Exception
{
System.out.println("Bean afterPropertiesSet.");
}
}通过设置default-destroy-method和default-init-method
对于同一配置文件下的所有的Bean都会使用该默认的初始化和销毁方法(但有特殊情况,见本篇总结部分)
1
2
3
4
5
6
7
<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"
default-destroy-method="defaultDestroy" default-init-method="defaultInit">
<bean id="beanLifeCycle" class="com.sh.imcdemo.services.impl.BeanLifeCycle"></bean>
</beans>com.sh.imcdemo.services.impl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.sh.imcdemo.services.impl;
/**
* Created by Mr SJL on 2016/11/26.
*
* @Author Junlan Shuai
*/
public class BeanLifeCycle
{
public void defaultInit()
{
System.out.println("Bean defaultInit.");
}
public void defaultDestroy()
{
System.out.println("Bean defaultDestory");
}
}总结
- 当三种方式同时使用时,我们会发现,第三种方式被覆盖了,另外两种方式的输出先后顺序是:先是2再是1。
- 当使用第3种方式时,实现类中不一定非要实现该默认方法,如果没有该方法,则没有处理。
- 当第2种和第3中方式同时使用时,默认方法却没有被覆盖,两者都会输出,但是第1种和第3种同时使用时,默认方法却被覆盖了。(???)
附录
测试基类 com.sh.imcdemo.unitTest
1 | package com.sh.imcdemo.unitTest; |
测试类com.sh.imcdemo.unitTest
1 | package com.sh.imcdemo.unitTest; |
依赖包pom.xml
1 | <spring.version>4.3.2.RELEASE</spring.version> |