Spring's AOP Quick Start

Fast write a Spring AOP implementation class

1. Define traffic class, using annotations added @Service Spring container.
@Service
public class the MyService {
  public String Print () {
    System.out.println ( "Print ...");
    return "End";
  }
}

1. Define aspect class 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.定义启动类
@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

Start
around advice to start
pre-notification
print ...
around the end of the notice End
post notice
returned to inform
End

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159929.htm