引言
Spring框架中在bean初始化和销毁时候执行某个方法的三种实现方式。- Spring框架中通过注解
@PostConastruct
和@PreDestroy
来实现Bean初始化执行和销毁时候执行方法; - Spring框架中通过实现接口
InitializingBean ,DisposableBean
来实现Bean初始化执行和销毁时候执行方法; - Spring框架中通过xml配置文件中bean的
init-method="" destroy-method=""
来实现Bean初始化执行和销毁时候执行方法;
一.Spring框架中通过注解@PostConastruct
和 @PreDestroy
来实现Bean初始化执行和销毁时候执行方法;
通过注解的方式推荐使用,后期spring boot也基本使用注解来配置,举个栗子:
package com.leftso.service;
import javax.annotation.PostConstruct;
public class TestService {
@PostConstruct
public void init(){
System.out.println("Bean 开始初始化啦。。");
}
public void dostory(){
System.out.println("Bean 销毁了。。。");
}
}
二.Spring框架中通过实现接口InitializingBean ,DisposableBean
来实现Bean初始化执行和销毁时候执行方法;
举个栗子:
package com.leftso.service;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class TestService implements InitializingBean,DisposableBean{
@Override
public void destroy() throws Exception {
System.out.println("Bean 销毁了。。。");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean 开始初始化啦。。");
}
}
三.Spring框架中通过xml配置文件中bean的init-method="" destroy-method=""
来实现Bean初始化执行和销毁时候执行方法;
举个例子:
<bean id="testService" class="com.leftso.service.TestService" init-method="init" destroy-method="destroy"></bean>
版权申明:本文为博主原创文章,未经博主允许不得转载。
https://www.leftso.com/blog/306.html
时效提示:本文最后更新于【 2018-04-01 21:30:21 】,某些文章具有时效性,若有错误或已失效,请在下方留言。
时效提示:本文最后更新于【 2018-04-01 21:30:21 】,某些文章具有时效性,若有错误或已失效,请在下方留言。
评论区域
评论功能已关闭. 提示:评论功能虽已关闭,关闭之前的评论仍然会展示。