自定义注解aop业务实现

例如定义一个自定义注解

 

  1. @Target({ElementType.METHOD, ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. public @interface Test {
  5.     String value();

}

  这个时候我们的注解就已经搞定了,接下来就是实现他的业务逻辑了。而实现他的业务是以aop的方式去实现的。 
在实现之前我们先去了解一下几个aop常用的注解 
aop常用的注解 
1、@Aspect作用是把当前类标识为一个切面供容器读取 
2、@before标识一个前置增强方法,相当于BeforeAdvice的功能 
3、@after final增强,不管是抛出异常或者正常退出都会执行 
4、@Pointcut定义切点 
5、@Around 

 

  1. @Aspect
  2. @Component
  3. public class OperateAspect {
  4.          @Pointcut("@annotation(com.junge.annotation.Test)")
  5.          public void annotationPointCut() {
  6.          }
  7. //       ​
  8.         @Before("annotationPointCut()")
  9.         public void before(JoinPoint joinPoint){
  10.            MethodSignature sign =  (MethodSignature)joinPoint.getSignature();
  11.            Method method = sign.getMethod();
  12.            Test annotation = method.getAnnotation(Test.class);
  13.            System.out.print("打印:"+annotation.value()+" 开始前");
  14.         }    
  15.         @Around("annotationPointCut()")
  16.         public Object advice(ProceedingJoinPoint joinPoint){
  17.             System.out.println("通知之开始");
  18.             Object retmsg=null;
  19.             try {
  20.                  retmsg=joinPoint.proceed();
  21.                 System.err.println("++++++++"+retmsg);
  22.             } catch (Throwable e) {
  23.                 e.printStackTrace();
  24.             }
  25.             System.out.println("通知之结束");
  26.             return retmsg;
  27.         }
  28.         @After("annotationPointCut()")
  29.         public void after() {
  30.              System.out.println("after方法执行后");
  31.         }

}

这样就实现了一个简单的自定义注解,如果你有自己的业务要写的话,你可以在某个方法里面写你的业务,比如记录操作日志,那么你就可以在@after方法里面写你的业务层代码。 
然后在你的接口上面可以加上@Test注解

  1. */
  2. @SpringBootApplication
  3. @RestController
  4. @EnableAspectJAutoProxy
  5. public class App 
  6. {
  7.     public static void main( String[] args )
  8.     {
  9. //        System.out.println( "Hello World!" );
  10.         SpringApplication.run(App.class, args);
  11.     }
  12.     @RequestMapping("/")
  13.     @Test("测试")
  14.     public List<String> getById() {
  15. //      haha();
  16.         System.err.println("o+++++++++++++++++");
  17.         List<String> list=new ArrayList<String>();
  18.         list.add("1");
  19.         list.add("qwe");
  20.         list.add("asd");
  21.         return list;
  22.     }
posted @ 2019-10-14 10:10  技术专家  阅读(431)  评论(0)    收藏  举报