【spring源码学习】Spring的IOC容器之BeanPostProcessor接口学习

一:含义作用

==>BeanPostProcessor接口是众多Spring提供给开发者的bean生命周期内自定义逻辑拓展接口中的一个

二:接口定义

package org.springframework.beans.factory.config;

import org.springframework.beans.BeansException;

public interface BeanPostProcessor {

    /**
     *IOC容器中的bean实例化之前执行
     */
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    /**
     *IOC容器中的bean实例化之后执行
     */
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}
View Code

三:自定义实例(在ioc实例化的时候执行,并打印内容。xml配置bean,或用注解注释,即可生效)

package com.mobile.thinks.manages.study;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor{

    /**
     * IOC容器中bean在被实例化之前执行该方法
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
            Class<?>  cls=bean.getClass();
            System.out.println("sxf  【自定义实例化之前】postProcessBeforeInitialization类路径==>"+cls);
            System.out.println("sxf  【自定义实例化之前】postProcessBeforeInitialization初始化对象的名字==>"+beanName);
        return bean;
    }

    
    /**
     * IOC容器中bean在被实例化之后执行该方法
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        Class<?>  cls=bean.getClass();
        System.out.println("sxf  【自定义实例化之后】postProcessBeforeInitialization类路径==>"+cls);
        System.out.println("sxf  【自定义实例化之后】postProcessBeforeInitialization初始化对象的名字==>"+beanName);
        return bean;
    }
    
    

}
View Code

四:spring内部例子

【1】org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor 类

==>在postProcessAfterInitialization 方法中,将bean中的方法标注有@Async注解的bean,不返回IOC真实的实例化对象,而是返回一个代理对象(动态代理)。org.springframework.scheduling.annotation.AsyncAnnotationAdvisor作为代理对象的执行增强(切面+增加)

【2】org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator 类

==>在postProcessAfterInitialization 方法中对bean进行动态代理。

原文地址:https://www.cnblogs.com/shangxiaofei/p/7206620.html