美文网首页其他
方法拦截器和自定义注解

方法拦截器和自定义注解

作者: 小鱼嘻嘻 | 来源:发表于2018-09-01 12:26 被阅读2次

自定义注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Duplicate {
    String value() default "test";
}

每一个元注解的含义可以参考这篇文章:
https://blog.csdn.net/vbirdbest/article/details/78822646

spring 拦截器

Advices:表示一个method执行前或执行后的动作。
Pointcut:表示根据method的名字或者正则表达式去拦截一个method。
Advisor:Advice和Pointcut组成的独立的单元,并且能够传给proxy factory 对象。

  • 定义切点和通知
@Component
public class DuplicateAdvisor implements InitializingBean {
    @Autowired
    HelloController helloController;

    private Pointcut pointcut;

    private Advice advice;

    /**
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        AspectJExpressionPointcut aspectJExpressionPointcut = new AspectJExpressionPointcut();
        aspectJExpressionPointcut.setExpression(
            "execution(* com.xiaoyu..*.*(..))");
        this.pointcut = aspectJExpressionPointcut;
        this.advice = new DuplicateInterceptor(helloController);
    }
}
  • 方法拦截器
public class DuplicateInterceptor implements MethodInterceptor {

    private HelloController helloController;

    public DuplicateInterceptor(HelloController helloController) {
        this.helloController = helloController;
    }

    /**
     * 拦截器
     *
     * @param methodInvocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Object[] arguments = methodInvocation.getArguments();
        Method method = methodInvocation.getMethod();
        Object proceed = methodInvocation.proceed();

        //获取annotation
        Duplicate duplicate = AnnotationUtils.findAnnotation(method, Duplicate.class);
        if (duplicate != null) {
            // business deal
        }
        return proceed;
    }
}

这里有两个知识点需要注意:

  • 在拦截器里面, @Autowired 和 @Resource是不生效的。那我们要注入怎么办呢?
    第一:可以在DuplicateAdvisor这里注入需要注入的类,然后在DuplicateInterceptor通过构造函数获取。也就是上面的实现方案
    第二:通过getBean()的方式获取bean
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        wac.getBean("helloController");

获取bean的方法: https://www.cnblogs.com/yjbjingcha/p/6752265.html

  • 在拦截器里如何使用自定义注解
    通过 Duplicate duplicate = AnnotationUtils.findAnnotation(method, Duplicate.class);可以获取到对应得自定义注意,然后根据是否有自定义注解来处理需要处理的业务。
    一个简单的应用场景,如果需要做防止重复提交的话,完全可以使用拦截器加注解的方式来实现。

相关文章

网友评论

    本文标题:方法拦截器和自定义注解

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