bean生命周期2
程序员文章站
2023-12-28 11:40:34
...
后处理bean BeanPostProcessor
1编写实现类
package com.itheima.e_lifecycle;
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;
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("前方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName)
throws BeansException {
System.out.println("后方法");
//目标对象
//生成jdk 代理 目的在目标方法前后执行(例如开启事务,提交事务)
return Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(),
bean.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("----开启事务");
//执行目标方法
Object obj = method.invoke(bean, args) ;
System.out.println("-----提交事务");
return obj;
}
}) ;
}
}
2配置
<!-- 将后处理bean的实现类注册给spring -->
<bean class="com.itheima.e_lifecycle.MyBeanPostProcessor"></bean>