快速写一个 Spring AOP 实现类
 
1.定义业务类,使用 @Service 注解加入 Spring 容器。
@Service
public class MyService {
  public String print() {
    System.out.println("print...");
    return "End";
  }
}
 
1.ASP站长网定义切面类,使用 @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

dawei

【声明】:九江站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。