Spring's AOP Quick Start

Fast write a Spring AOP implementation class

  1. Traffic class is defined, annotations added using @Service Spring container.
@Service
public class MyService {
  public String print() {
    System.out.println("print...");
    return "End";
  }
}
  1. Class definitions section, using annotations added @Component Spring container, such as a cut label @Aspect represents the class, and to a method for labeling the type of notification.

    Notification type
    • Before advice
    • After returning advice
    • Back to News
    • Abnormal notice
    • Around advice
@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. Define start classes
@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);

  }
}

Export

启动
环绕通知开始
前置通知
print...
环绕通知结束End
后置通知
返回通知
End

Guess you like

Origin www.cnblogs.com/bigshark/p/11318778.html