POJ - 2352-Stars ( 树状数组 )

Spark之takeOrdered,取前几个数据

  返回  

7.spring篇-@Aspect切面

2021/8/20 18:22:19 浏览:

文章目录

  • 1.spring篇-@Aspect切面
    • 1.1 简单使用
      • 1.1.1 使用注解说明
      • 1.1.2 使用例子
    • 1.2 入口
      • 1.2.1 入口注解@EnableAspectJAutoProxy
      • 1.2.2 AspectJAutoProxyRegistrar注册动态信息流程
        • 1、AspectJAutoProxyRegistrar使用ImportBeanDefinitionRegistrar的bean定义注册
        • 2、注册AnnotationAwareAspectJAutoProxyCreator切面动态代理类
        • 3、AspectJAutoProxyRegistrar的wrapIfNecessary的代理流程
        • 4、 获取拦截器Advisor通知类
        • 5、生成动态代理

1.spring篇-@Aspect切面

1.1 简单使用

1.1.1 使用注解说明

  • @Aspect:作用是把当前类标识为一个切面供容器读取
  • @Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
  • @Around:环绕增强,相当于MethodInterceptor
  • @AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行
  • @Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有
  • @AfterThrowing:异常抛出增强,相当于ThrowsAdvice
  • @After: final增强,不管是抛出异常或者正常退出都会执行

1.1.2 使用例子

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author yinyuming
 * Created by yinyuming on 2021/2/18 9:57
 */
@Aspect
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = false, exposeProxy = true)
public class AspectConfigService {

    @Pointcut("execution(* com.yym.frame.springboot.logging.*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知类型");
        return joinPoint.proceed();
    }

    @After("execution(* com.yym.frame.springboot.logging.*.*(..))")
    public void after() throws Throwable {
        System.out.println("后置通知类型");
    }
}

1.2 入口

1.2.1 入口注解@EnableAspectJAutoProxy

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
	/**
	 * 是否需要类代理,proxyTargetClass=true时,类代理使用Cglib。false则使用jdk动态代理
	 * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
	 * to standard Java interface-based proxies. The default is {@code false}.
	 */
	boolean proxyTargetClass() default false;
	/**
	 * 将实例放入org.springframework.aop.framework.AopContext的ThreadLocal中,
	 * 可以使用(AopContext.currentProxy()) 静态调用返回当前上下文的代理对象
	 * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
	 * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
	 * Off by default, i.e. no guarantees that {@code AopContext} access will work.
	 * @since 4.3.1
	 */
	boolean exposeProxy() default false;
}

1.2.2 AspectJAutoProxyRegistrar注册动态信息流程

1、AspectJAutoProxyRegistrar使用ImportBeanDefinitionRegistrar的bean定义注册

2、注册AnnotationAwareAspectJAutoProxyCreator切面动态代理类

动态代理核心处理类,类图如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ltoRFmtJ-1629454909566)(image/AnnotationAwareAspectJAutoProxyCreator.png)]

解释一下一些基类和接口的功能,且AnnotationAwareAspectJAutoProxyCreator的实现
1、BeanPostProcessor,InstantiationAwareBeanPostProcessor,SmartInstantiationAwareBeanPostProcessor
实现这些接口,spring就会在bean的前,后或是提前暴露等地方调用这些切入面方法。(则代理实现是通过bean初始化过程中,给原bean生成代理对象返回)
2、BeanFactoryAware
实现将获取bean工厂对象,(则代理实现,通过获取bean工厂中的使用@Aspect注解的类)

3、AspectJAutoProxyRegistrar的wrapIfNecessary的代理流程

	/**
	 * 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) {
	    //是否生成过代理对象
		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;
		}

		// 是否生成代理对象,获取代理生成的拦截器,默认是Advisor拦截器,Create proxy if we have advice.
		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;
	}

4、 获取拦截器Advisor通知类

AbstractAdvisorAutoProxyCreator类

	@Override
	@Nullable
	protected Object[] getAdvicesAndAdvisorsForBean(
			Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
        //获取对当前bean需要拦截的Advisor
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

大多对选择代理的拦截器逻辑处理都在,org.springframework.aop.support.AopUtils,
Advisor的生成Advice通知对象,下面举例几个通知接口

  • MethodBeforeAdvice
  • AfterReturningAdvice

获取Advisor的流程

  • 1、通过bean工厂获取Advisor类型的bean
  • 2、通过bean工厂获取@Aspect注解类,检查该类的下面的方法声明通知,生成Advisor(ReflectiveAspectJAdvisorFactory使用该类生成)
	@Override
	protected List<Advisor> findCandidateAdvisors() {
		//通过bean工厂获取Advisor类型的bean
		List<Advisor> advisors = super.findCandidateAdvisors();
		//通过bean工厂获取@Aspect注解类,检查该类的下面的方法声明通知,生成Advisor
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}

5、生成动态代理

    //生成代理对象
	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);
		//设置是否是要代理类,代理类需要使用cglib代理
		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());
	}

ProxyFactory代理工厂的生成,DefaultAopProxyFactory的createAopProxy

	@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.");
			}
			//接口类直接使用,jdk动态代理
			if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
				return new JdkDynamicAopProxy(config);
			}
			//
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			return new JdkDynamicAopProxy(config);
		}
	}

联系我们

如果您对我们的服务有兴趣,请及时和我们联系!

服务热线:18288888888
座机:18288888888
传真:
邮箱:888888@qq.com
地址:郑州市文化路红专路93号