栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第十二章、后置处理Bean

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第十二章、后置处理Bean

BeanPostProcessor作⽤:对Spring⼯⼚所
创建的对象,进⾏再加⼯。
AOP底层实现:
注意:BeanPostProcessor接⼝
 xxxx(){
 }
1.后置处理Bean的运⾏原理分析


假如实现了BeanPostProcessor接口。
顺序:
1.反射通过调用构造方法创建对象。
2.DI注入。
3.postProcessBeforeInitiallization()方法加工。
4.postProcessBeforeInitiallization()方法加工后通过返回值将对象交给Spring。
5.InitializingBean初始化和自定义的初始化操作后Spring将对象交给postProcessAfterInitiallization()方法。
6.postProcessAfterInitiallization()方法加工。
7.postProcessAfterInitiallization()方法加工后通过返回值将对象交给Spring。
8.Spring再把对象交换给客户。让客户使用。

程序员实现BeanPostProcessor规定接⼝中的⽅法:
Object postProcessBeforeInitiallization(Object bean String beanName)
作⽤:Spring创建完对象,并进⾏注⼊后,可以运⾏Before⽅法进⾏加⼯获得Spring创建好的对象 :通过⽅法的参数最终通过 return 返回值交给Spring框架.
Object postProcessAfterInitiallization(Object bean String beanName)
作⽤:Spring执⾏完对象的初始化操作后,可以运⾏After⽅法进⾏加⼯
获得Spring创建好的对象 :通过⽅法的参数最终通过 return 返回值交给Spring框架。

实战中:
很少处理Spring的初始化操作:没有必要区分Before After。只需要实现其中的⼀个After⽅法即可。
注意:
只实现After方法时也要将Before 方法写出来 只是方法内不写代码,只需要将对象返回给Spring。Before方法可以什么都不做,但是要把对象给Spring。然后Spring再把对象给After方法。即:

Object postProcessBeforeInitiallization(Object bean String beanName){
 return bean对象
}
Object postProcessAfterInitiallization(Object bean String beanName){
    
--------    实现代码   ------------
    return bean对象
    
}
2.BeanPostProcessor的开发步骤 步骤1.类 实现 BeanPostProcessor接⼝
public class MyBeanPostProcessor implements BeanPostProcessor{
 @Override
 public Object postProcessBeforeInitialization(Object bean, String
beanName) throwsBeansException {
 return bean;
 }
 @Override 
 public Object postProcessAfterInitialization(Object bean, String
beanName) throws BeansException {
 Categroy categroy = (Categroy) bean;//因为是Object类型 所以要强转一下
 categroy.setName("xiaowb");
 return categroy;
 }
}
步骤2.Spring的配置⽂件中进⾏配置

3.BeanPostProcessor细节


只要是在此配置文件中配置的对象,MyBeanPostProcessor都会对它们进行加工。而MyBeanPostProcessor可能只需要传其中的一个对象,所以需要判断一下。

将下面这段代码:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
 Categroy categroy = (Categroy) bean;//因为是Object类型 所以要强转一下
 categroy.setName("xiaowb");
 return categroy;
 }
改成:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if(bean instanceof Categroy){
 Categroy categroy = (Categroy) bean;//因为是Object类型 所以要强转一下
 categroy.setName("xiaowb");
    }
 return bean;//这里返回bean或者categroy都可以 因为此时bean已经被强转成categroy
 }

本系列文章从Spring5原理开始深入浅出,从工厂特性=>依赖注入–IOC=>AOP编程=>Spring事务=>纯注解开发。本文来自观看B站孙帅Spring教程后做的笔记。持续更新…

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/711964.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号