Bean的生命周期

Spring Bean Life Cycle

Spring框架提供了以下4种控制bean生命周期事件的方法:

1、InitializingBean和DisposableBean回调接口
2、用于特定行为的其他Aware接口
3、bean配置文件中的自定义init()和destroy()方法
4、注解@PostConstruct和@PreDestroy

1)InitializingBean和DisposableBean回调接口

org.springframework.beans.factory.InitializingBean接口 允许bean在容器设置bean的所有必要属性后执行初始化工作.

InitializingBean接口只有一个方法:

void afterPropertiesSet() throws Exception;

这不是初始化bean的首选方法,因为它将bean类与spring容器紧密结合。 更好的方法是在applicationContext.xml文件中的bean定义中使用“init-method”属性。

类似地,实现org.springframework.beans.factory.DisposableBean接口允许bean在包含它的容器被销毁时获得回调。

DisposableBean接口只有一个方法:

void destroy() throws Exception;

一个简单的例子如下:

package com.howtodoinjava.task;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
 
public class DemoBean implements InitializingBean, DisposableBean
{
    //Other bean attributes and methods
     
    @Override
    public void afterPropertiesSet() throws Exception
    {
        //Bean initialization code
    }
     
    @Override
    public void destroy() throws Exception
    {
        //Bean destruction code
    }
}

2)用于特定行为的其他Aware接口

Spring提供了一系列Aware接口,允许bean向容器指示它们需要某种基础结构依赖。 每个接口都需要您实现一个方法来在bean中注入依赖项。

这些接口可以概括为:

Aware接口覆盖的方法作用
ApplicationContextAwarevoid setApplicationContext (ApplicationContext applicationContext) throws BeansException;为实现此接口的bean注入ApplicationContext
ApplicationEventPublisherAwarevoid setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher);设置此对象运行的ApplicationEventPublisher
BeanClassLoaderAwarevoid setBeanClassLoader (ClassLoader classLoader);将bean类加载器提供给bean实例
BeanFactoryAwarevoid setBeanFactory (BeanFactory beanFactory) throws BeansException;将拥有工厂提供给bean实例
BeanNameAwarevoid setBeanName(String name);将创建此bean的bean工厂中的bean名称注入bean实例
BootstrapContextAwarevoid setBootstrapContext (BootstrapContext bootstrapContext);设置此对象运行的BootstrapContext。
LoadTimeWeaverAwarevoid setLoadTimeWeaver (LoadTimeWeaver loadTimeWeaver);将LoadTimeWeaver设置bean实例
MessageSourceAwarevoid setMessageSource (MessageSource messageSource);将MessageSource注入bean实例
NotificationPublisherAwarevoid setNotificationPublisher (NotificationPublisher notificationPublisher);注入NotificationPublisher
PortletConfigAwarevoid setPortletConfig (PortletConfig portletConfig);注入PortletContext
ResourceLoaderAwarevoid setResourceLoader (ResourceLoader resourceLoader);注入ResourceLoader
ServletConfigAwarevoid setServletConfig (ServletConfig servletConfig);注入ServletConfig
ServletContextAwarevoid setServletContext (ServletContext servletContext);注入ServletContext

一个简单的例子如下:

package com.howtodoinjava.task;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
 
public class DemoBean implements ApplicationContextAware,
        ApplicationEventPublisherAware, BeanClassLoaderAware, BeanFactoryAware,
        BeanNameAware, LoadTimeWeaverAware, MessageSourceAware,
        NotificationPublisherAware, ResourceLoaderAware
{
    @Override
    public void setResourceLoader(ResourceLoader arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setNotificationPublisher(NotificationPublisher arg0) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void setMessageSource(MessageSource arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setLoadTimeWeaver(LoadTimeWeaver arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanName(String arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanClassLoader(ClassLoader arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        // TODO Auto-generated method stub
    }
}

3) bean配置文件中的自定义init()和destroy()方法

bean配置文件中的默认init和destroy方法可以通过两种方式定义:

  • 适用于单个bean的本地定义
  • 使用于所有bean的全局定义

本地定义:

<beans>
 
    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"
                    init-method="customInit"
                    destroy-method="customDestroy"></bean>
 
</beans>

全局定义: <beans>标签下的所有bean都使用设置初始化和销毁方法,当所有bean使用同一个模式定义init和destory方法名称时非常有用,此功能可帮助您不要单独配置所有bean的init和destroy方法名称。

<beans default-init-method="customInit" default-destroy-method="customDestroy">  
 
        <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>
 
</beans>
package com.howtodoinjava.task;
 
public class DemoBean
{
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }
 
    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}

4)注解@PostConstruct和@PreDestroy

从Spring 2.5开始,您还可以使用注解@PostConstruct和@PreDestroy指定生命周期方法。

  • 在使用默认构造函数构造bean之后,在将实例返回到请求对象之前,将调用@PostConstruct注释方法。

  • @PreDestroy注释的方法在Bean被容器销毁之前调用。

简单例子如下:

package com.howtodoinjava.task;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 
public class DemoBean
{
    @PostConstruct
    public void customInit()
    {
        System.out.println("Method customInit() invoked...");
    }
     
    @PreDestroy
    public void customDestroy()
    {
        System.out.println("Method customDestroy() invoked...");
    }
}

转载于:https://my.oschina.net/killnull/blog/1929017

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值