Spring中bean的执行初始化和销毁方法的4种方式详解

一、引入

在java的实际开发过程中,我们可能需要在spring实例化一个bean的过程中,使用到初始化一个对象(bean)后立即初始化(加载)一些数据,或者在销毁一个对象之前进行执行一些事情等等。
因此Spring为我们提供了一系列的方式:

方式初始化 init销毁destroy
1@bean 注解,指定属性initMethod@bean 注解,指定属性destroyMethod
2xml形式,指定 init-methodxml形式,指定 destroy-method
3实现InitializingBean接口,重写afterPropertiesSet方法实现DisposableBean接口,重写destroy方法
4注解@PostConstruct注解@PreDestroy

二、方式详解

  1. @bean 注解

 @Bean(name="user",initMethod = "init",destroyMethod = "destroy")
 public User user(String name) {
     return new User(name);
 }
  1. xml形式

<bean id="user" class="com.demo.user" init-method="init" destroy-method="destroy"></bean>
  1. 接口InitializingBean和DisposableBean
    实现InitializingBean接口,重写afterPropertiesSet()方法

public interface InitializingBean {

   /**
    * Invoked by the containing {@code BeanFactory} after it has set all bean properties
    * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
    * <p>This method allows the bean instance to perform validation of its overall
    * configuration and final initialization when all bean properties have been set.
    * @throws Exception in the event of misconfiguration (such as failure to set an
    * essential property) or if initialization fails for any other reason
    */
   void afterPropertiesSet() throws Exception;

}

实现DisposableBean方法,重写destroy方法

/**
 * Interface to be implemented by beans that want to release resources
 * on destruction. A BeanFactory is supposed to invoke the destroy
 * method if it disposes a cached singleton. An application context
 * is supposed to dispose all of its singletons on close.
 *
 * <p>An alternative to implementing DisposableBean is specifying a custom
 * destroy-method, for example in an XML bean definition.
 * For a list of all bean lifecycle methods, see the BeanFactory javadocs.
 *
 * @author Juergen Hoeller
 * @since 12.08.2003
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
 * @see org.springframework.context.ConfigurableApplicationContext#close
 */
public interface DisposableBean {

	/**
	 * Invoked by a BeanFactory on destruction of a singleton.
	 * @throws Exception in case of shutdown errors.
	 * Exceptions will get logged but not rethrown to allow
	 * other beans to release their resources too.
	 */
	void destroy() throws Exception;

}
  1. @PostConstruct和@PreDestroy

//初始化后执行的方法,必须为voidlei'xing类型
 @PostConstruct
 public void init() {
 ***do someThing
 }

//bean销毁前执行的方法
@PreDestroy
public void init() {
***do someThing
}

从Java EE 5规范开始,Servlet中增加了两个影响Servlet生命周期的注解:@PostConstruct和@PreDestroy。
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。

三、总结

一)对Spring版本的要求

  • xml和实现接口的方式是Spring最原始的方式,Spring任何版本均支持

  • @PostConstruct和@PreDestroy需要Spring2.5及以上版本

  • @bean :需要Spring 3.0以上版本支持

    二)执行顺序不一样
    其中
    此处引入Spring中bean生命周期的介绍

在这里插入图片描述引自: 深究Spring中Bean的生命周期.

初始化之后执行顺序: @PostConstruct > InitializingBean > Beaninit-method(xml注解或者@Bean)

销毁之前执行顺序:@preDestroy > DisposableBean > destoryMethod(xml注解或者@Bean)

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进朱者赤

多多支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值