美文网首页
在SpringBoot2.0.2的版本中,使用AspectJ通过

在SpringBoot2.0.2的版本中,使用AspectJ通过

作者: 吃竹子的程序熊 | 来源:发表于2020-03-16 20:28 被阅读0次

SpringBoot 2.0.2 + ASPECT +ANNOTATION +INTERFACE

在SpringBoot2.0.2的版本中,使用AspectJ通过@Annotation来进行切面处理,如果被注解定义在接口上,切面不会生效。

解决方法: 自定义切面处理类,处理指定的注解。

实现


import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.Joinpoint;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 对自定义注解进行切面处理的自定义类
 *
 * @author Hanqi <jpanda@aliyun.com>
 * @since 2018/12/10 14:43
 */
public class AnnotationAspectPointCutAdvisor extends AbstractPointcutAdvisor {

    /**
     * 需要处理的切面注解
     */
    private Class<? extends Annotation> targetAnnotation = Autowired.class;

    /**
     * 方法拦截处理器
     */
    private final MethodInterceptor interceptor;
    /**
     * 切入点
     */
    private final StaticMethodMatcherPointcut pointcut = new AnnotationAspectPoint();

    public AnnotationAspectPointCutAdvisor() {
        this(Joinpoint::proceed);
    }

    protected AnnotationAspectPointCutAdvisor(MethodInterceptor interceptor) {
        this.interceptor = interceptor;
    }

    @Override
    public Pointcut getPointcut() {
        return pointcut;
    }


    @Override
    public Advice getAdvice() {
        return interceptor;
    }

    private final class AnnotationAspectPoint extends StaticMethodMatcherPointcut {

        @Override
        public boolean matches(Method method, Class<?> targetClass) {

            assert targetAnnotation != null;

            return AnnotationUtils.findAnnotation(method, targetAnnotation) != null
                    || AnnotationUtils.findAnnotation(targetClass, targetAnnotation) != null;
        }
    }

    public void setTargetAnnotation(Class<? extends Annotation> targetAnnotation) {
        this.targetAnnotation = targetAnnotation;
    }
}

相关文章

网友评论

      本文标题:在SpringBoot2.0.2的版本中,使用AspectJ通过

      本文链接:https://www.haomeiwen.com/subject/xamoehtx.html