Spring AOP 的实现机制
首先是上面这篇文章,介绍了spring aop的实现原理。jdk动态代理的原理是利用InvocationHandler和Proxy两个类。
public static void main(String[] args) {
UserDefineInvocationHandler invocationHandler = new UserDefineInvocationHandler();
Class[] interfaces = {SpeakInterface.class, EatInterface.class};
SpeakInterface obj = invocationHandler.getProxy(interfaces,new Person());
obj.speak("invok");
}
public interface SpeakInterface {
void speak(String words);
}
public interface EatInterface {
void eat();
}
public class Person implements SpeakInterface {
@Override
public void speak(String words) {
System.out.println("speak:" + words);
}
}
public class UserDefineInvocationHandler implements InvocationHandler {
private Object obj ;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(obj,args);
}
public T getProxy(Class[] interfaces,Object object){
this.obj = object;
return (T) Proxy.newProxyInstance(object.getClass().getClassLoader(),interfaces, this);
}
}
首先通过Proxy.newProxyInstance返回接口的代理,同时也传入了对应的InvocationHandler,当调用接口的时候,会调用Handler的invoke方法,然后通过反射调用对应实现类的方法。
其中要注意的是,Person只实现了SpeakInterface,但是实例化代理类的时候,多传入了EatInterface接口,可以正常执行。其次在invoke方法中,Object proxy,这个类不是接口的实现类,通过debug发现是Handler自身的引用。
以上是jdk动态代理的原理,接下来是spring中是如何实现的。
spring中bean加载过程里面说了spring中bean的加载过程
在AbstractAutowireCapableBeanFactory类的doCreateBean方法中
......
try {
this.populateBean(beanName, mbd, instanceWrapper);//设置属性,依赖关系
exposedObject = this.initializeBean(beanName, exposedObject, mbd);//对bean进行判断是否要创建代理
} catch (Throwable var18) {
if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
throw (BeanCreationException)var18;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
}
......
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
this.invokeAwareMethods(beanName, bean);
return null;
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); //在方法之前织入代码
}
try {
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);//在方法之后植入代码
}
return wrappedBean;
}
applyBeanPostProcessorsBeforeInitialization,applyBeanPostProcessorsAfterInitialization这两个方法最终都调用了AbstractAutoProxyCreator类的createProxy方法。
以applyBeanPostProcessorsAfterInitialization的调用为例
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
//当bean对象有合适的advisor的时候创建代理
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;
}
在createProxy方法中
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);
}
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);//设置对应的advisor
proxyFactory.setTargetSource(targetSource);//设置对应的bean对象,用于后续的cglib代理或者jdk代理
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
//这地方获取代理的时候,一直会深入到AopProxy接口的getProxy方法,这个接口有两个实现,一个是jdk代理,一个是cglib代理
return proxyFactory.getProxy(getProxyClassLoader());
}
首先ProxyFactory 类是继承ProxyCreatorSupport,在实例化的时候,aopProxyFactory会初始化,然后在getProxy方法的时候,会返回不同的AopProxy接口的实现
关于cglib的动态代理,可以看cglib动态代理过程,但是那篇文章的前置加载过程没有这篇文章将的清楚,可以合一起看
/**
* Create a new ProxyCreatorSupport instance.
*/
public ProxyCreatorSupport() {
this.aopProxyFactory = new DefaultAopProxyFactory();
}
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
}
至此,我们获取到了对应的jdk代理的代理类
JdkDynamicAopProxy是一个比较清晰的类,实现了InvocationHandler,AopProxy接口,和文章开头讲的aop动态代理一样,就下来是代用invoke方法使用。
现在是整体调用的脉络清晰了,中间还有很多细节的东西没弄清楚,比如好几个使用缓存的地方,还不知道具体作用是做什么。
后面有空再仔细看看