Spring4-bean生命周期-4- 实例化Bean后置处理器(继承BeanPostProcessor)InstantiationAwareBeanPostProcessor

Spring4-bean生命周期-4- 实例化Bean后置处理器(继承BeanPostProcessor)InstantiationAwareBeanPostProcessor_第1张图片

 

一、接口:

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
    //调用时机为bean实例化(Instantiation)之前 
    //如果返回了bean实例, 则会替代原来正常通过target bean生成的bean的流程
    //典型的例如aop返回proxy对象. 此时bean的执行流程将会缩短, 只会执行 BeanPostProcessor#postProcessAfterInitialization接口完成初始化。
    Object postProcessBeforeInstantiation(Class var1, String var2) throws BeansException;



    //调用时机为bean实例化(Instantiation)之后和任何初始化(Initialization)之前
    boolean postProcessAfterInstantiation(Object var1, String var2) throws BeansException;



    PropertyValues postProcessPropertyValues(PropertyValues var1, PropertyDescriptor[] var2, Object var3, String var4) throws BeansException;
}

二、InstantiationAwareBeanPostProcessor与BeanPostProcessor对比

  1.  BeanPostProcessor 执行时机为bean初始化(Initialization)阶段,日常可以拓展该接口对bean初始化进行定制化处理。
  2.  InstantiationAwareBeanPostProcessor 执行时机bean实例化(Instantiation)阶段,典型用于替换bean默认创建方式,例如aop通过拓展接口生成代理对应,主要用于基础框架层面。如果日常业务中需要拓展该,spring推荐使用适配器类InstantiationAwareBeanPostProcessorAdapter。
  3. 所有bean创建都会进行回调。

 三、adapter

package com.ooo.life;

import java.beans.PropertyDescriptor;

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

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

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

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

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

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

 

你可能感兴趣的:(Spring学习和理解)