5, 注解spring-springaop的实现源码

小demo

我们现实一个简单的aop增强demo

  • 添加依赖
# 新添
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-aspects</artifactId>
	<version>5.2.8.RELEASE</version>
</dependency>

有一个类TestBean51, 它有一个方法test, 我们要对test进行增强

@Component
public class TestBean51 {

    public void test(String  name){
        System.out.println("hello, " + name);
    }
}

一个简单的增强类AspectBean, 用来对TestBean51进行增强实现

@Component
@Aspect
public class AspectBean {

    @Pointcut("execution(* top.itkaoti.test05.TestBean51.test(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(){
        System.out.println("before.........");
    }

    @After("pointcut()")
    public void after(){
        System.out.println("after.........");
    }
}

主函数

@Configuration
@EnableAspectJAutoProxy
public class SpringTest05 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext("top.itkaoti.test05");
        TestBean51 testBean51 = (TestBean51)annotationConfigApplicationContext.getBean("testBean51");
        testBean51.test("xiaodoubi");
    }
}

-->
before.........
hello, xiaodoubi
after.........
<--

源码追踪

这边我们知道testBean51返回的是一个代理对象, 那我们直接debug想办法定位代理对象生成的地方

--1, AnnotationConfigApplicationContext.java-->
public AnnotationConfigApplicationContext(String... basePackages) {
	this();
	// 扫包(先不看)
	scan(basePackages);
	// 点进去
	refresh();
}

--2, AbstractApplicationContext-->
## 在这一步的时候, 虽然我们之前debug过, 知道单例的Bean是在finishBeanFactoryInitialization面生成的, 我们可以在此前后打上断点, 查看运行前后是否有生成testBean51的代理类来判断
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		prepareRefresh();
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		prepareBeanFactory(beanFactory);
		try {
			postProcessBeanFactory(beanFactory);
			invokeBeanFactoryPostProcessors(beanFactory);
			registerBeanPostProcessors(beanFactory);
			initMessageSource();
			initApplicationEventMulticaster();
			onRefresh();
			registerListeners();
			// testBean51是在这边生成的,点进去
			finishBeanFactoryInitialization(beanFactory);
			finishRefresh();
		}
		catch (BeansException ex) {
			...
		}
		finally {
			...
		}
	}
}

--3, AbstractApplicationContext-->
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	...
    beanFactory.preInstantiateSingletons();
}

--4, DefaultListableBeanFactory-->
@Override
public void preInstantiateSingletons() throws BeansException {
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    for (String beanName : beanNames) {
        if (isFactoryBean(beanName)) {
            // 工厂bean
            ...
        }else{
            // 普通bean
            getBean(beanName);
        }
    }
}

这边和前面讲解的基本类似,小逗比这边就直接跳过, 进入到关键地方。

dcuaJH.png

大家可以直接在AbstractAutowireCapableBeanFactory 的initializeBean方法打上断点。

--5, AbstractAutowireCapableBeanFactory-->
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
	...
	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
	    // 初始化之前调用的
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
	    // bean的init方法调用
		invokeInitMethods(beanName, wrappedBean, mbd);
	}
	catch (Throwable ex) {
		...
	}
	if (mbd == null || !mbd.isSynthetic()) {
	    // 初始化之后调用的, 点进去
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}
	return wrappedBean;
}


--6, AbstractAutowireCapableBeanFactory-->
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
		throws BeansException {

	Object result = existingBean;
	// 一些列的BeanPostPorcessor遍历调用
	for (BeanPostProcessor processor : getBeanPostProcessors()) {
	    // 其中有一个AnnotationAwareAspectjAutoProxyCreator, 我们点进去
		Object current = processor.postProcessAfterInitialization(result, beanName);
		if (current == null) {
			return result;
		}
		result = current;
	}
	return result;
}

dctQr4.png

--7, AbstractAutoProxyCreator-->
# 记住这边我们的bean还是原来的bean, 非代理对象
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            // 点进去
            return this.wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

--8, AbstractAutoProxyCreator-->
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
	...
	Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
	if (specificInterceptors != DO_NOT_PROXY) {
		this.advisedBeans.put(cacheKey, Boolean.TRUE);
		// 创建了代理对象, 点进去
		Object proxy = createProxy(
				bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
		this.proxyTypes.put(cacheKey, proxy.getClass());
		// 直接返回了代理对象
		return proxy;
	}
	this.advisedBeans.put(cacheKey, Boolean.FALSE);
	return bean;
}

--9, AbstractAutoProxyCreator-->
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
		@Nullable Object[] specificInterceptors, TargetSource targetSource) {

	if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
		AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
	}
    // spring使用工厂类来做代理的生成
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.copyFrom(this);

	if (!proxyFactory.isProxyTargetClass()) {
		if (shouldProxyTargetClass(beanClass, beanName)) {
			proxyFactory.setProxyTargetClass(true);
		}
		else {
			evaluateProxyInterfaces(beanClass, proxyFactory);
		}
	}
    // 一些设置
	Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
	proxyFactory.addAdvisors(advisors);
	proxyFactory.setTargetSource(targetSource);
	customizeProxyFactory(proxyFactory);

	proxyFactory.setFrozen(this.freezeProxy);
	if (advisorsPreFiltered()) {
		proxyFactory.setPreFiltered(true);
	}
    // 点进去
	return proxyFactory.getProxy(getProxyClassLoader());
}

--10, ProxyFactory-->
public Object getProxy(@Nullable ClassLoader classLoader) {
    // createAopProxy() 点进去
	return createAopProxy().getProxy(classLoader);
}

--11, ProxyCreatorSupport-->
protected final synchronized AopProxy createAopProxy() {
	if (!this.active) {
		activate();
	}
	// createAopProxy点进去
	return getAopProxyFactory().createAopProxy(this);
}
--12, DefaultAopProxyFactory-->
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
	if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
		Class<?> targetClass = config.getTargetClass();
		if (targetClass == null) {
			...
		}
		// 是接口使用jdk动态代理
		if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
			return new JdkDynamicAopProxy(config);
		}
		// 否者使用cglib代理
		return new ObjenesisCglibAopProxy(config);
	}
	else {
		return new JdkDynamicAopProxy(config);
	}
}

到这里我们就结束了spring的aop代理对象生成的全过程, spring把一系列的操作封装到了BeanPostProcessor中。

BeanPostProcessor

dcKjUS.png

BeanPostProcessor有2个方法, 见名知意, 这是在Bean初始化前和后调用的。

/**
 * 刚好今天是情人节, 我们今天就以带女票出去逛街为例
 *
 * 1, 我们要租车(留下了穷的眼泪)
 * 2, 开车到女票家
 * 3, 带女票去市里
 * 4, 逛街
 * 5, 把女票送回家(为啥就回家了??????,感觉拥有了一大片森林)
 * 6, 开车去组车公司
 * 7, 还车
 *
 * 大家有没有发现,这边出了逛街之外, 其他的刚好是一对一对的, 我们就(强行)封装起来
 */
// 逛街 留下了英语差的眼泪
public class Guangjie{

    public void gj(){
        System.out.println("逛街");
    }
}


public class Drive1 implements BeanPostProcessor{
    public  Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("开车去女票家");
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("开车去租赁公司");
        return bean;
    }

}


public class Drive2 implements BeanPostProcessor{
    public  Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("开车去市中心");
        return bean;
    }
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("开车送女票回家");
        return bean;
    }

}
--SpringTest06-->
public class SpringTest06 {

    public static void main(String[] args) {
        ArrayList<BeanPostProcessor> processors = new ArrayList();
        RendAndLoanCar rendAndLoanCar = new RendAndLoanCar();
        Drive1 drive1 = new Drive1();
        Drive2 drive2 = new Drive2();
        processors.addAll(Arrays.asList(rendAndLoanCar, drive1, drive2));

        for (BeanPostProcessor beanPostProcessor: processors){
            beanPostProcessor.postProcessBeforeInitialization(null, null);
        }
        new Guangjie().gj();
        for (int i = processors.size()-1; i >=0 ; i--) {
            processors.get(i).postProcessAfterInitialization(null, null);
        }
//        for (BeanPostProcessor beanPostProcessor: processors){
//             beanPostProcessor.postProcessAfterInitialization(null, null);
//        }
    }
}

-->
租车
开车去女票家
开车去市中心
逛街
开车送女票回家
开车去租赁公司
还车
<--

就和我们之前看的的, spring把很多东西封装成了BeanPostProcessor

总结

今天我们学习springaop的源码, 查看了spring是如何一步一步的创建出了代理对象, 当然这里面有很多细节我们都直接略过了, 后面我们可以在进一步深入的了解, 除此之外, 我们通过了一个小demo理解了BeanPostProcessor的基本原理。

springtest5项目源码

springtest6项目源码