Spring AOP如何產生代理對象

框架就是複雜的留給自己,簡單的留給碼農,像寫hello world一樣簡單

早年開發Spring AOP程序時,都是xml文件配置aop(現在不流行xml了,註解@EnableAspectJAutoProxy大行其道),然後框架解析,

例如:

它這種配置是如何解析的,攔截方法怎麼拿到,注入到代理,代理對象如何生成,

看下文,可以先參考我的博文bean創建過程一個Spring Bean從無到有的過程

xml元素解析就不具體說了,感興趣自己研究

 由於我用的tag是<aop:config>,那麼解析類就是ConfigBeanDefinitionParser,解析時會註冊一個AspectJAwareAdvisorAutoProxyCreator,一個高高高級的BeanPostProcessor

 

 

 然後解析aop:config子元素,由於方法衆多,我只寫了大塊

if (POINTCUT.equals(localName)) {
				parsePointcut(elt, parserContext);
			}
			else if (ADVISOR.equals(localName)) {
				parseAdvisor(elt, parserContext);
			}
			else if (ASPECT.equals(localName)) {
				parseAspect(elt, parserContext);
			}

參照https://blog.csdn.net/dong19891210/article/details/105697175創建bean的createBeanInstance(產出原生對象)和initializeBean階段,對應文件org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

 

/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 * <p>Called from {@link #createBean} for traditionally defined beans,
	 * and from {@link #initializeBean} for existing bean instances.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @return the initialized bean instance (potentially wrapped)
	 * @see BeanNameAware
	 * @see BeanClassLoaderAware
	 * @see BeanFactoryAware
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #invokeInitMethods
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
		//.......略

		if (mbd == null || !mbd.isSynthetic()) {
			System.out.println(beanName+" AOP 6666666666666666");
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
			System.out.println(wrappedBean.getClass()+" AOP 888888888888");
		}
		return wrappedBean;
	}

 

@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		System.out.println("對象:"+existingBean+"  的類型是:"+existingBean.getClass());
		List<BeanPostProcessor> beanPostProcessorList = getBeanPostProcessors();
		System.out.println("BeanPostProcessor列表: "+beanPostProcessorList);

		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			//Bean初始化之後
			System.out.println(beanProcessor.getClass().getName());
			result = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (result == null) {
				return result;
			}
		}
		return result;
	}

在for之前輸出:

calculator AOP 6666666666666666
對象:spring.aop.CalculatorImp@906d29b  的類型是:class spring.aop.CalculatorImp
BeanPostProcessor列表: [org.springframework.context.support.ApplicationContextAwareProcessor@49d3c823, org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker@436bc36, org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor@3b8f0a79, org.springframework.context.annotation.ConfigurationClassPostProcessor$EnhancedConfigurationBeanPostProcessor@71e693fa, proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false, org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@4f6f416f, org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@409c54f, org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor@3e74829, org.springframework.context.support.PostProcessorRegistrationDelegate$ApplicationListenerDetector@5fe1ce85]

 獲取所有的BeanPostProcessor,

進入for階段後,留意一個org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator 的處理

處理方式可以細看,由於代碼超多,只展示大方面的代碼

還記得上面說過的註冊的一個bean:AspectJAwareAdvisorAutoProxyCreator,它繼承自org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(Object bean, String beanName) throws BeansException

/**
	 * Create a proxy with the configured interceptors if the bean is
	 * identified as one to proxy by the subclass.
	 * @see #getAdvicesAndAdvisorsForBean
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (!this.earlyProxyReferences.contains(cacheKey)) {
                //
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}
/**
	 * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
	 * @param bean the raw bean instance
	 * @param beanName the name of the bean
	 * @param cacheKey the cache key for metadata access
	 * @return a proxy wrapping the bean, or the raw bean instance as-is
	 */
	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		//。。。。。略

		// Create proxy if we have advice.預備創建代理對象,拿到攔截方法
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		if (specificInterceptors != DO_NOT_PROXY) {
			System.out.println("org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(Object bean, String beanName) ");

			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			//spring aop產生“代理對象”的地方
			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;
	}

 在創建代理對象前,會拿到通知或攔截方法

1. 拿攔截方式org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource)

2. 創建代理  Object org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource)

/**
	 * Create an AOP proxy for the given bean.
	 * @param beanClass the class of the bean
	 * @param beanName the name of the bean
	 * @param specificInterceptors the set of interceptors that is
	 * specific to this bean (may be empty, but not null)
	 * @param targetSource the TargetSource for the proxy,
	 * already pre-configured to access the bean
	 * @return the AOP proxy for the bean
	 * @see #buildAdvisors
	 */
	protected Object createProxy(
			Class<?> beanClass, String beanName, 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);
		for (Advisor advisor : advisors) {
			proxyFactory.addAdvisor(advisor);
		}

		proxyFactory.setTargetSource(targetSource);
		customizeProxyFactory(proxyFactory);

		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}
        
        //創建代理
		return proxyFactory.getProxy(getProxyClassLoader());
	}

文件org.springframework.aop.framework.proxyFactory.java 

/**
	 * Create a new proxy according to the settings in this factory.
	 * <p>Can be called repeatedly. Effect will vary if we've added
	 * or removed interfaces. Can add and remove interceptors.
	 * <p>Uses the given class loader (if necessary for proxy creation).
	 * @param classLoader the class loader to create the proxy with
	 * (or {@code null} for the low-level proxy facility's default)
	 * @return the proxy object
	 */
	public Object getProxy(ClassLoader classLoader) {
		return createAopProxy().getProxy(classLoader);
	}

 


public class ProxyCreatorSupport extends AdvisedSupport {
//。。。略
/**
	 * Create a new ProxyCreatorSupport instance.
	 */
	public ProxyCreatorSupport() {
		this.aopProxyFactory = new DefaultAopProxyFactory();
	}
    /**
	 * Return the AopProxyFactory that this ProxyConfig uses.
	 */
	public AopProxyFactory getAopProxyFactory() {
		return this.aopProxyFactory;
	}
    
   /**
	 * Subclasses should call this to get a new AOP proxy. They should <b>not</b>
	 * create an AOP proxy with {@code this} as an argument.
	 */
	protected final synchronized AopProxy createAopProxy() {
		if (!this.active) {
			activate();
		}
		return getAopProxyFactory().createAopProxy(this);
	}
}


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.");
			}
			//如果targetClass是接口,則使用JDK生成代理proxy
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				return new JdkDynamicAopProxy(config);
			}
			//若不是接口,則使用cglib生成代理類proxy
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}
}

 由於我用的是接口,那麼代理實現類是JdkDynamicAopProxy.java

/**
 * JDK-based {@link AopProxy} implementation for the Spring AOP framework,
 * based on JDK {@link java.lang.reflect.Proxy dynamic proxies}.
 *
 * <p>Creates a dynamic proxy, implementing the interfaces exposed by
 * the AopProxy. Dynamic proxies <i>cannot</i> be used to proxy methods
 * defined in classes, rather than interfaces.
 *
 * <p>Objects of this type should be obtained through proxy factories,
 * configured by an {@link AdvisedSupport} class. This class is internal
 * to Spring's AOP framework and need not be used directly by client code.
 *
 * <p>Proxies created using this class will be thread-safe if the
 * underlying (target) class is thread-safe.
 *
 * <p>Proxies are serializable so long as all Advisors (including Advices
 * and Pointcuts) and the TargetSource are serializable.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Dave Syer
 * @see java.lang.reflect.Proxy
 * @see AdvisedSupport
 * @see ProxyFactory
 */
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
	
	/** Config used to configure this proxy */
	private final AdvisedSupport advised;


	/**
	 * Construct a new JdkDynamicAopProxy for the given AOP configuration.
	 * @param config the AOP configuration as AdvisedSupport object
	 * @throws AopConfigException if the config is invalid. We try to throw an informative
	 * exception in this case, rather than let a mysterious failure happen later.
	 */
	public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
		Assert.notNull(config, "AdvisedSupport must not be null");
		if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("No advisors and no TargetSource specified");
		}
		this.advised = config;
	}


	@Override
	public Object getProxy() {
		return getProxy(ClassUtils.getDefaultClassLoader());
	}

	@Override
	public Object getProxy(ClassLoader classLoader) {
		if (logger.isDebugEnabled()) {
			logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
		}
		Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        //jdk自帶的工具
		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
	}

/**
	 * Implementation of {@code InvocationHandler.invoke}.
	 * <p>Callers will see exactly the exception thrown by the target,
	 * unless a hook method throws an exception.
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		MethodInvocation invocation;
		Object oldProxy = null;
		boolean setProxyContext = false;

		TargetSource targetSource = this.advised.targetSource;
		Class<?> targetClass = null;
		Object target = null;

		try {
			if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
				// The target does not implement the equals(Object) method itself.
				return equals(args[0]);
			}
			else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
				// The target does not implement the hashCode() method itself.
				return hashCode();
			}
			else if (method.getDeclaringClass() == DecoratingProxy.class) {
				// There is only getDecoratedClass() declared -> dispatch to proxy config.
				return AopProxyUtils.ultimateTargetClass(this.advised);
			}
			else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
					method.getDeclaringClass().isAssignableFrom(Advised.class)) {
				// Service invocations on ProxyConfig with the proxy config...
				return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
			}

			Object retVal;

			if (this.advised.exposeProxy) {
				// Make invocation available if necessary.
				oldProxy = AopContext.setCurrentProxy(proxy);
				setProxyContext = true;
			}

			// May be null. Get as late as possible to minimize the time we "own" the target,
			// in case it comes from a pool.
			//得到目標對象
			target = targetSource.getTarget();
			if (target != null) {
				targetClass = target.getClass();
			}

			// Get the interception chain for this method.
			// 得到定義好的攔截器鏈
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

			// Check whether we have any advice. If we don't, we can fallback on direct
			// reflective invocation of the target, and avoid creating a MethodInvocation.
			if (chain.isEmpty()) {
				// We can skip creating a MethodInvocation: just invoke the target directly
				// Note that the final invoker must be an InvokerInterceptor so we know it does
				// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
				// We need to create a method invocation...
				/*
				 * 如果有攔截器的定義,那麼需要調用攔截器後才能調用目標對象的相應方法
				 * 
				 */
				invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				// Proceed to the joinpoint through the interceptor chain.
				// 
				retVal = invocation.proceed();
			}

			// Massage return value if necessary.
			Class<?> returnType = method.getReturnType();
			if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
					!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
				// Special case: it returned "this" and the return type of the method
				// is type-compatible. Note that we can't help if the target sets
				// a reference to itself in another returned object.
				retVal = proxy;
			}
			else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
				throw new AopInvocationException(
						"Null return value from advice does not match primitive return type for: " + method);
			}
			return retVal;
		}
		finally {
			if (target != null && !targetSource.isStatic()) {
				// Must have come from TargetSource.
				targetSource.releaseTarget(target);
			}
			if (setProxyContext) {
				// Restore old proxy.
				AopContext.setCurrentProxy(oldProxy);
			}
		}
	}

此時已是代理對象

然後一層層返回:

 

代理對象執行業務方法,順便加些其他操作

 

總結:Spring AOP的處理由它AspectJAwareAdvisorAutoProxyCreator對bean的處理,還是對bean的生命週期的把控,在哪個階段生成,initializeBean階段,然後再去看怎麼生成的代理對象,需要什麼原材料(攔截器,通知,切面,切入點等),哪種方式(兩種方式)

好了,細節慢慢深入,相信嗎,Spring aop爲創建代理對象,方法嵌套調用上百個,還有不少新概念,不過還好,對於開發人員用起aop來像helloword一樣簡單。

 

附圖兩張:

參考:

0. https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#xsd-schemas-aop

1. https://www.springframework.org/schema/aop/spring-aop.xsd

2. http://www.docjar.com/html/api/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java.html

3. https://github.com/seaswalker/spring-analysis/blob/master/note/spring-aop.md

4. Spring 框架的設計理念與設計模式分析 https://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/index.html

5. Understanding Spring AOP  https://www.codejava.net/frameworks/spring/understanding-spring-aop

6. Spring 源碼學習(八) AOP 使用和實現原理

http://www.justdojava.com/2019/07/17/spring-analysis-note-8/

7. Spring AOP 源碼初窺(三)掃描Advice與Bean匹配  https://segmentfault.com/a/1190000016054658

8. Spring AOP 使用介紹,從前世到今生 https://www.javadoop.com/post/spring-aop-intro

9. spring源碼解析之AOP原理 https://www.cnblogs.com/liuyk-code/p/9886033.html

10. Spring AOP Example Tutorial – Aspect, Advice, Pointcut, JoinPoint, Annotations, XML Configuration 

https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations

11. Spring Core Middleware 源碼分析二:Spring AOP 之 @AspectJ https://www.shangyang.me/2017/04/15/spring-middleware-sourcecode-analysis-02-spring-aop-aspect/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章