Spring之bean后处理器的运用

本文详细介绍了Spring框架中的Bean后处理器机制,包括其实现原理、使用场景及如何自定义Bean后处理器来增强容器中的Bean。通过示例展示了如何在Bean初始化前后进行处理,并实现了返回值转换的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring 提供了一种bean ,这种bean 并不对外提供服务,无需id 属性,但它负责对容器中的其他bean 执行处理,例如为容器中的目标bean 生成代理。这种bean 可称为bean后处理器,它在bean 实例创建成功后,对其进行进一步的加强处理。
bean 后处理器必须实现BeanPostProcessor 接口,该接口包含两个方法:

1)、

@Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return null;
    }

该方法第一个参数是系统即将初始化的bean 实例:第二个参数是bean实例的名字

2)、

@Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        // TODO Auto-generated method stub
        return null;
    }

该方法的第一个参数是系统刚完成初始化的bean 实例:第二个参数
是bean 实例的名字

以上两个方法在容器中的每个bean 执行
初始化方法前后分别调用



栗子:


一、定义一个接口

package com.hk.spring.ba05;

public interface ISomeSerice {

    public String doFirst();
    public void doSecond();
}


二、接口的实现类

package com.hk.spring.ba05;

public class ISomeServiceImpl implements ISomeSerice {

    public ISomeServiceImpl() {
        System.out.println("无参构造函数运行");
    }

    @Override
    public String doFirst() {

        System.out.println("执行doFirst");
        return "hello";
    }

    @Override
    public void doSecond() {

        System.out.println("执行doSecond");
    }

}


三、自定义bean后处理器

package com.hk.spring.ba05;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 *  在postProcessAfterInitialization中增强bean的有返回值的方法,使之返回值字母全部变成大写
 * @author 浪丶荡
 *
 */
public class MyBeanPostProcessor implements BeanPostProcessor{

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessBeforeInitialization执行");
        return bean;//把执行before后的bean返回
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, String beanName)
            throws BeansException {
        //增强bean
        Object proxy = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(), 
                    new InvocationHandler() {

                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args)
                                throws Throwable {
                            Object result = method.invoke(bean, args);
                            if(result!=null){
                                result = ((String) result).toUpperCase();
                            }
                            return result;
                        }
                    }
                    );
        System.out.println("postProcessAfterInitialization执行");
        return proxy;//把增强的代理类返回
    }

}


四、容器的配置(applicationContext.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">

    <!-- 注册 service对象 ISomeSerice iSomeService = new ISomeServiceImpl();
            创建的时间是Spring容器被初始化是时候
    -->
    <bean id="someService" class="com.hk.spring.ba05.ISomeServiceImpl"/>
    <!-- 注册bean后处理器 -->
    <bean class="com.hk.spring.ba05.MyBeanPostProcessor"/>

</beans>

五、测试类

package com.hk.spring.ba05;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
    @Test
    public void test_1(){
        //加载Spring配置文件 创建Spring容器对象
        String resource = "/com/hk/spring/ba05/applicationContext.xml";
        ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
        //从容器中获取指定bean对象
        ISomeSerice iSomeService = (ISomeSerice) ac.getBean("someService");
        String result = iSomeService.doFirst();
        iSomeService.doSecond();
        System.out.println(result);

    }
}

结果

无参构造函数运行
postProcessBeforeInitialization执行
postProcessAfterInitialization执行
执行doFirst
执行doSecond
HELLO

分析

bean后处理器在容器初始化时执行

ISomeSerice iSomeService = (ISomeSerice) ac.getBean("someService");

这个iSomeService就是被增强了的bean。

以上是增强所有bean的有字符串返回的方法,如果需要增强特定的bean

增强特定的bean

package com.hk.spring.ba05;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
 *  在postProcessAfterInitialization中<br>增强特定bean,使之有返回值的方法字母全部变成大写
 * @author 浪丶荡
 *
 */
public class MyBeanPostProcessor implements BeanPostProcessor{

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("postProcessBeforeInitialization执行");
        return bean;//把执行before后的bean返回
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, String beanName)
            throws BeansException {

        if ("someService".equals(beanName)) {//增强特定的bean
            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(), new InvocationHandler() {

                        @Override
                        public Object invoke(Object proxy, Method method,
                                Object[] args) throws Throwable {
                            Object result = method.invoke(bean, args);
                            if (result != null) {
                                result = ((String) result).toUpperCase();
                            }
                            return result;
                        }
                    });
            return proxy;//把增强的代理类返回
        }
        System.out.println("postProcessAfterInitialization执行");
        return bean;//什么也不做,把原bean返回
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值