其他

方法拦截器和自定义注解

2018-09-01  本文已影响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;
    }
}

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

        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        wac.getBean("helloController");

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

上一篇 下一篇

猜你喜欢

热点阅读