春:春AOPは、エージェントを作成します

1.水戸

ここに画像を挿入説明

2.概要

薬を探して、以前の記事を参照してください。

3.前文概要

/**
	 * 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
	 *
	 * 如果需要则包装该bean,例如该bean可以被代理
	 */
	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		// 1、如果已经处理过或者不需要创建代理,则返回
		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.
		// 2、创建代理
		// 2.1 根据指定的bean获取所有的适合该bean的增强
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		if (specificInterceptors != DO_NOT_PROXY) {
			// 2.2 为指定bean创建代理
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

		// 3、缓存
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

ここでは第二の主要ステップは、プロキシを作成することです

プロキシを作成します。4.

/**
	 * 为给定的bean创建代理
	 *
	 * 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, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

		// 1、当前beanFactory是ConfigurableListableBeanFactory类型,则尝试暴露当前bean的target class
		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}

		// 2、创建ProxyFactory并配置
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.copyFrom(this);

		// 是否直接代理目标类以及接口
		if (!proxyFactory.isProxyTargetClass()) {
			// 确定给定bean是否应该用它的目标类而不是接口进行代理
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			// 检查给定bean类上的接口,如果合适的话,将它们应用到ProxyFactory。即添加代理接口
			else {
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}

		// 3、确定给定bean的advisors,包括特定的拦截器和公共拦截器,是否适配Advisor接口。
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		// 设置增强
		proxyFactory.addAdvisors(advisors);
		// 设置代理目标
		proxyFactory.setTargetSource(targetSource);
		// 定制proxyFactory(空的模板方法,可在子类中自己定制)
		customizeProxyFactory(proxyFactory);

		// 锁定proxyFactory
		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}

		// 4、创建代理
		return proxyFactory.getProxy(getProxyClassLoader());
	}

特定のプロセス・エージェントの作成4.1

	public Object getProxy(@Nullable ClassLoader classLoader) {
		return createAopProxy().getProxy(classLoader);
	}

	/**
	 * 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);
	}

私たちは、委託による特定の仕事へのプロキシを作成し、上記のコードから見ることができる方法。AopProxyFactorycreateAopProxy

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

	@Override
	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
		// 1、判断是否需要创建CGLIB动态代理
		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.");
			}
			// todo 这里有疑问 即
			// targetClass.isInterface()
			// Proxy.isProxyClass(targetClass)
			// 什么情况下会生效
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				// 创建jdk动态代理
				return new JdkDynamicAopProxy(config);
			}
			// 创建CGLIB动态代理
			return new ObjenesisCglibAopProxy(config);
		}
		// 2、默认创建JDK动态代理
		else {
			return new JdkDynamicAopProxy(config);
		}
	}

ここでは、最終的に判定条件とインタビューが共通の問題が発生しますで判断CGLIB JDKのダイナミックプロキシを参照してください。

動的プロキシCGLIBを作成する必要性を決定します

  1. config.isOptimize():で判断しCGLIB、エージェントの最適化戦略を作成するかどうか
    の値のための条件をProxyConfigクラスoptimize属性。この属性は、エージェントの最適化をマークするかどうか。スタートの最適化は、通常、プロキシオブジェクトが作成された後、強化の修正を有効にするには、デフォルト値そうではないことを意味しますfalse場合exposeProxyあなたは、に設定trueしても、optimizeとしてtrue、それは無視されます。
  2. config.isProxyTargetClass():設定されているproxy-target-classtrue
    条件の値ProxyConfigクラスproxyTargetClassの属性。この属性は、プロキシの場合ではなく、インターフェース生成エージェントを介してターゲットクラスに直接マークされています。
  3. hasNoUserSuppliedProxyInterfaces(config):プロキシインタフェースがあります

任意の上記の3つの条件が開いて考える満足CGLIB動的プロキシが、これにif決意条件で他の層が存在するtargetClass.isInterface() || Proxy.isProxyClass(targetClass)ターゲット自体は、インタフェースクラス、標的クラス、またはによるものである場合、すなわち、Proxy.newProxyInstance()或Proxy.getProxyClass()まだ使用して、生成jdk動的プロキシを。

4.2動的プロキシCGLIBを取得

	@Override
	public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
		}

		try {
			Class<?> rootClass = this.advised.getTargetClass();
			Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

			Class<?> proxySuperClass = rootClass;
			if (ClassUtils.isCglibProxyClass(rootClass)) {
				proxySuperClass = rootClass.getSuperclass();
				Class<?>[] additionalInterfaces = rootClass.getInterfaces();
				for (Class<?> additionalInterface : additionalInterfaces) {
					this.advised.addInterface(additionalInterface);
				}
			}

			// Validate the class, writing log messages as necessary.
			validateClassIfNecessary(proxySuperClass, classLoader);

			// Configure CGLIB Enhancer...
			// 新建并配置Enhancer
			Enhancer enhancer = createEnhancer();
			if (classLoader != null) {
				enhancer.setClassLoader(classLoader);
				if (classLoader instanceof SmartClassLoader &&
						((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
					enhancer.setUseCache(false);
				}
			}
			enhancer.setSuperclass(proxySuperClass);
			enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));

			Callback[] callbacks = getCallbacks(rootClass);
			Class<?>[] types = new Class<?>[callbacks.length];
			for (int x = 0; x < types.length; x++) {
				types[x] = callbacks[x].getClass();
			}
			// fixedInterceptorMap only populated at this point, after getCallbacks call above
			enhancer.setCallbackFilter(new ProxyCallbackFilter(
					this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
			enhancer.setCallbackTypes(types);

			// Generate the proxy class and create a proxy instance.
			// 生成代理类并创建代理实例
			return createProxyClassAndInstance(enhancer, callbacks);
		}
		catch (CodeGenerationException | IllegalArgumentException ex) {
			throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
					": Common causes of this problem include using a final class or a non-visible class",
					ex);
		}
		catch (Throwable ex) {
			// TargetSource.getTarget() failed
			throw new AopConfigException("Unexpected AOP exception", ex);
		}
	}

その後を見て春量Aop CGLIBダイナミックプロキシの呼び出し:春

4.3 JDKのダイナミックプロキシを取得

@Override
	public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
		}
		// 确定用于给定AOP配置的代理的完整接口集。
		Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		// 判断被代理接口有没有重写equals和hashCode方法
		findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
		// 为接口创建代理
		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
	}

その後を見て春量Aop JDKの動的プロキシの呼び出し:春

リリース1017元の記事 ウォンの賞賛435 ビュー126万+

おすすめ

転載: blog.csdn.net/qq_21383435/article/details/104018140