spring源码学习BeanPostProcessor接口学习

Posted 无信不立

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring源码学习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内部例子

以上是关于spring源码学习BeanPostProcessor接口学习的主要内容,如果未能解决你的问题,请参考以下文章

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记

对于学习Spring源码的感悟