zoukankan      html  css  js  c++  java
  • Spring的AOP快速上手

    快速写一个 Spring AOP 实现类

    1. 定义业务类,使用 @Service 注解加入 Spring 容器。
    @Service
    public class MyService {
      public String print() {
        System.out.println("print...");
        return "End";
      }
    }
    
    1. 定义切面类,使用 @Component 注解加入 Spring 容器,标注 @Aspect 表示此类为切面类,并给方法标注通知类型。

    通知类型

    • 前置通知
    • 后置通知
    • 返回通知
    • 异常通知
    • 环绕通知
    @Aspect
    @Component
    public class MyAspect {
    
      @Pointcut("execution(* com.xxx.MyService.*(..))")
      public void pointCut() {
      }
    
      @Before("pointCut()")
      public void start() {
        System.out.println("前置通知");
      }
    
      @After("pointCut()")
      public void end() {
        System.out.println("后置通知");
      }
    
      @AfterReturning("pointCut()")
      public void returnStart() {
        System.out.println("返回通知");
      }
    
      @AfterThrowing("pointCut()")
      public void exceptionStart() {
        System.out.println("异常通知");
      }
    
      @Around("pointCut()")
      public Object startAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知开始");
        Object proceed = joinPoint.proceed(joinPoint.getArgs());
        System.out.println("环绕通知结束" + proceed);
        return proceed;
      }
    }
    
    1. 定义启动类
    @EnableAspectJAutoProxy
    @ComponentScan
    public class App {
      public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
    
        MyService service = context.getBean(MyService.class);
        System.out.println("启动");
        String print = service.print();
        System.out.println(print);
    
      }
    }
    

    输出

    启动
    环绕通知开始
    前置通知
    print...
    环绕通知结束End
    后置通知
    返回通知
    End
    
  • 相关阅读:
    安装pgsql
    ln软连接
    vsftp上传失败
    redis配置systemctl
    jmeter 录制排除模式
    数据库基本操作
    按日期排序
    angularjs的cache
    angularjs路由传递参数
    angularjs路由相关知识
  • 原文地址:https://www.cnblogs.com/bigshark/p/11318778.html
Copyright © 2011-2022 走看看