Spring纯注解实现AOP

1、pom文件中导入相关依赖

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.8.RELEASE</version>
    </dependency>

2、创建业务逻辑类

@Service("productService")
public class ProductService {
    public void queryProduct() throws Exception {
//        throw new Exception("运行时异常!");
        System.out.println("查询商品信息中!");
    }
}

3、创建切面和通知

@Aspect
@Component
public class ProductLog {
    /**
     * 切点
     */
    @Pointcut("execution(public void com.qing.zhao.ProductService.*(..))")
    public void pc(){}

    /**
     * 以下方法都是通知
     */
    @Before("pc()")
    public void beforQueryProduct(){
        System.out.println("查询商品信息-----前");
    }
    
    @After("pc()")
    public void afterQueryProduct(){
        System.out.println("查询商品信息-----后");
    }
    
    @AfterReturning("pc()")
    public void returnQueryProduct(){
        System.out.println("查询商品信息-----正常返回");
    }
    
    @AfterThrowing("pc()")
    public void exceptionQueryProduct(){
        System.out.println("查询商品信息-----异常返回");
    }
    
    @Around("pc()")
    public void aroundQueryProduct(ProceedingJoinPoint joinPoint){
        try {
            System.out.println("查询商品信息-----前");
            joinPoint.proceed();
            System.out.println("查询商品信息-----后");
        } catch (Throwable throwable) {
            System.out.println("查询商品信息-----异常返回");
            throwable.printStackTrace();
        }finally {
            System.out.println("查询商品信息-----最终返回");
        }

    }

4、创建配置类

@Configuration
@ComponentScan
@EnableAspectJAutoProxy
public class Configration {

}

5、运行结果

  • 无异常正常返回:

在这里插入图片描述

  • 有异常返回:

在这里插入图片描述

  • 环绕无异常正常返回:
    在这里插入图片描述

  • 环绕有异常返回:
    在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章