7.spring篇-@Aspect切面

7 篇文章 0 订阅

1.spring篇-@Aspect切面

代码版本

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.0.10.RELEASE</version>
      <scope>compile</scope>
    </dependency>

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切面动态代理类

动态代理核心处理类,类图如下:

请添加图片描述

解释一下一些基类和接口的功能,且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);
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值