Spring中Bean的生命周期

1、Spring bean 生命周期相关接口
    Spring bean生命周期过程中涉及的相关接口可分为如下几类:

    1)、Bean自身的方法:这个包括了Bean本身调用的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法

    2)、Bean级生命周期接口方法:这个包括了BeanNameAware、BeanFactoryAware、ApplicationContextAware、InitializingBean和DiposableBean这些接口的方法

    3)、容器级生命周期接口方法:这个包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

    4)、工厂后处理器接口方法:这个包括了BeanFactoryPostProcessor、AspectJWeavingEnabler, ConfigurationClassPostProcessor, CustomAutowireConfigurer等等非常有用的工厂后处理器接口的方法。工厂后处理器也是容器级的。在应用上下文装配配置文件之后立即调用。

2、生命周期过程接口调用实例验证

1)、首先是一个简单的Spring Bean,调用Bean自身的方法和 Bean级生命周期接口方法 ,为了方便演示,它实现了 BeanNameAware、
BeanFactoryAware、ApplicationContextAwareInitializingBean和DiposableBean接口,同时有2个方法,对应配置文件中<bean>的init-method和destroy-method。如下:
package com.xl.springtest;

import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Created by xl on 2016/6/22.
 */
public class Student  implements BeanFactoryAware,BeanNameAware,
InitializingBean,DisposableBean,ApplicationContextAware {

private BeanFactory beanFactory;
    private ApplicationContext applicationContext;
    private String  beanName ;


     private String name ;
     private String address;
     private String Phone;

    public Student() {
        System.out.println("这是Student实现类无参数构造器!!");
}

public Student(String name, String address, String phone) {
this.name = name;
        this.address = address;
Phone = phone;
System.out.println("这是Student实现类 带参数 构造器!!");
}

public String getAddress() {

return address;
}

public void setAddress(String address) {
        System.out.println("【注入属性】注入属性address");
        this.address = address;
}

public String getPhone() {
return Phone;
}

public void setPhone(String phone) {
        System.out.println("【注入属性】注入属性phone");
Phone = phone;
}

public String getName() {
return name;
}

public void setName(String name) {
        System.out.println("【注入属性】注入属性name");
        this.name = name;
}

/**
     * 这是ApplicationContextAware接口方法
* @param applicationContext
* @throws BeansException
     */
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware 接口 ,setApplicationContext()方法被调用");
        this.applicationContext = applicationContext;
}

/**
     * 这是BeanFactoryAware接口方法
* @param beanFactory
* @throws BeansException
     */
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware 接口 ,setBeanFactory()方法被调用");
            this.beanFactory = beanFactory;
}

/**
     *  // 这是BeanNameAware接口方法
* @param name
*/
@Override
public void setBeanName(String name) {
        System.out.println("BeanNameAware 接口 ,setBeanName()方法被调用");
           this.beanName = beanName;
}

/**
     * 这是DisposableBean接口方法
* @throws Exception
     */
@Override
public void destroy() throws Exception {
        System.out.println("DisposableBean 接口 ,destroy()方法被调用");

}

/**
     * 这是InitializingBean接口方法
* @throws Exception
     */
@Override
public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean 接口 ,afterPropertiesSet()方法被调用");

}

/**
     *   通过<bean>的init-method属性指定的初始化方法
*/
public void myInit() {
          System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
}

/**
     *  通过<bean>的destroy-method属性指定的初始化方法
*/
public void myDestory() {
           System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
}

@Override
public String toString() {
return "Student{" +
"address='" + address + '\'' +
", Phone='" + Phone + '\'' +
", name='" + name + '\'' +
'}';
}
}
2)、接下来是实现BeanFactoryPostProcessor接口的工厂后置处理器类,如下:
package com.xl.springtest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * Created by xl on 2016/6/22.
 */
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
public MyBeanFactoryPostProcessor() {
super();
System.out.println("这是MyBeanFactoryPostProcessor实现类构造器!!");
}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        System.out.println("BeanFactoryPostProcessor调用postProcessBeanFactory方法");
BeanDefinition bd = beanFactory.getBeanDefinition("student");
bd.getPropertyValues().addPropertyValue("phone","1399999999");

}
}
3)、 接下来是实现 BeanPostProcessor 接口的后置处理器类,如下:
package com.xl.springtest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;

/**
 * Created by xl on 2016/6/22.
 */
public class MyBeanPostProcessor implements BeanPostProcessor {

public MyBeanPostProcessor() {
        System.out.println("这是MyBeanPostProcessor实现类构造器!!");
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor  postProcessBeforeInitialization 方法被调用");
        return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor  postProcessAfterInitialization 方法被调用");
        return bean;
}
}
4)、下面是 InstantiationAwareBeanPostProcessor  接口实现类,InstantiationAwareBeanPostProcessor 本质是BeanPostProcessor的子接口,一般继承Spring为其提供的适配器类 InstantiationAwareBeanPostProcessor Adapter来使用它,如下:
package com.xl.springtest;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

import java.beans.PropertyDescriptor;

/**
 * Created by xl on 2016/6/22.
 */
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

public MyInstantiationAwareBeanPostProcessor() {
super();
System.out.println("这是MyInstantiationAwareBeanPostProcessorAdapter实现类构造器!!");
}

// 接口方法、实例化Bean之前调用
@Override
public Object postProcessBeforeInstantiation(Class beanClass,
String beanName) throws BeansException {
        System.out.println("MyInstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法");
      return null;
}

// 接口方法、实例化Bean之后调用
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {
      System.out.println("MyInstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法");
        return bean;

}
// 接口方法、设置某个属性时调用
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs,
PropertyDescriptor[] pds, Object bean, String beanName)throws BeansException {
       System.out.println("InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法");
            return pvs;
}

}
5)、 Bean 配置文件bean-life.xml如下:
<?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 id="myBeanPostProcessor" class="com.xl.springtest.MyBeanPostProcessor"/>

       <bean id="myMyInstantiationAwareBeanPostProcessor" class="com.xl.springtest.MyInstantiationAwareBeanPostProcessor"/>

       <bean id="myBeanFactoryPostProcessor" class="com.xl.springtest.MyBeanFactoryPostProcessor"/>

       <bean id="student" class="com.xl.springtest.Student" init-method="myInit" destroy-method="myDestory" >
             <property name="address" value="一路21号"/>
              <property name="name" value="xxl"/>
              <property name="phone" value="1388888888"/>

<!--
              <constructor-arg index="0" value="xxl"/>
              <constructor-arg index="1" value="一路21号"/>
              <constructor-arg index="2" value="1388888888"/>
         -->
</bean>

</beans>

6)、测试应用程序:
public static void main(String args[] ){

    ApplicationContext appContext = new ClassPathXmlApplicationContext("bean-life.xml");

Student student = appContext.getBean("student",Student.class);
System.out.println(student);

System.out.println("现在开始关闭容器!");
((ClassPathXmlApplicationContext)appContext).registerShutdownHook();
}

7)、验证结果输出
这是MyBeanFactoryPostProcessor实现类构造器!!
BeanFactoryPostProcessor调用postProcessBeanFactory方法
这是MyBeanPostProcessor实现类构造器!!
这是MyInstantiationAwareBeanPostProcessorAdapter实现类构造器!!
MyInstantiationAwareBeanPostProcessor调用postProcessBeforeInstantiation方法
这是Student实现类无参数构造器!!
InstantiationAwareBeanPostProcessor调用postProcessPropertyValues方法
【注入属性】注入属性address
【注入属性】注入属性name
【注入属性】注入属性phone
BeanNameAware 接口 ,setBeanName()方法被调用
BeanFactoryAware 接口 ,setBeanFactory()方法被调用
ApplicationContextAware 接口 ,setApplicationContext()方法被调用
MyBeanPostProcessor  postProcessBeforeInitialization 方法被调用
InitializingBean 接口 ,afterPropertiesSet()方法被调用
【init-method】调用<bean>的init-method属性指定的初始化方法
MyBeanPostProcessor  postProcessAfterInitialization 方法被调用
MyInstantiationAwareBeanPostProcessor调用postProcessAfterInitialization方法
Student{address='一路21号', Phone='1399999999', name='xxl'}
现在开始关闭容器!
DisposableBean 接口 ,destroy()方法被调用
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法
Process finished with exit code 0


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值