自定义Aop注解

首先声明自己的注解。

  1. @Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.METHOD })public @interface MyAop {}

其次编写拦截器

  1. public class SimpleInterceptor implements MethodInterceptor {
  2. public static boolean called = false;
  3. public Object invoke(MethodInvocation invocation) throws Throwable {
  4. called = true;
  5. try {
  6. System.out.println("before... ");
  7. Object returnData = invocation.proceed();
  8. System.out.println("after...");
  9. return returnData;
  10. } catch (Exception e) {
  11. System.out.println("throw...");
  12. throw e;
  13. }
  14. }
  15. }

最后,配置拦截器的筛选器。筛选所有标记了 MyAop 注解的 Bean 都使用我们的拦截器,我们在 Module 中进行如下声明:

  1. public class MyAopSetup implements Module {
  2. public void loadModule(ApiBinder apiBinder) throws Throwable {
  3. //1.任意类
  4. Matcher<Class<?>> atClass = AopMatchers.anyClass();
  5. //2.有MyAop注解的方法
  6. Matcher<Method> atMethod = AopMatchers.annotatedWithMethod(MyAop.class);
  7. //3.让@MyAop注解生效
  8. apiBinder.bindInterceptor(atClass, atMethod, new SimpleInterceptor());
  9. }
  10. }