Spring学习-第三节-AspectJ注解

  1. 配置类
package spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * 概述:
 * 作者:zhujie
 * 创建时间:2021/11/02 10:59
 */
@Configuration
@ComponentScan(basePackages = {"spring"})
@EnableAspectJAutoProxy//开启代理
public class SpringConfig {

}

  1. 被代理类
package spring.aspectj;

import org.springframework.stereotype.Service;

/**
 * 概述:
 * 作者:zhujie
 * 创建时间:2021/11/02 11:12
 */
@Service
public class UserService {
    public void add(){
        int a = 10/0;
        System.out.println("add方法执行");
    }
}

  1. 代理类
package spring.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 概述:
 * 作者:zhujie
 * 创建时间:2021/11/02 11:13
 */
@Component
@Aspect
@Order(1)
public class UserProxy {

    @Pointcut(value = "execution(* spring.aspectj.UserService.add(..))")
    public void point(){};

    @Before(value = "point()")
    public void before(){
        System.out.println("前置通知before......");
    }

    @After(value = "point()")
    public void after(){
        System.out.println("最终通知after.....");
    }

    @Around(value = "point()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前around.....");
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后around.....");
    }

    @AfterThrowing(value = "point()")
    public void afterThrowing(){
        System.out.println("异常通知afterThrowing.....");
    }

    @AfterReturning(value = "point()")
    public void afterReturning(){
        System.out.println("后置通知afterReturning.....");
    }

}

  1. 测试类
package spring.aspectj;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import spring.config.SpringConfig;

/**
 * 概述:
 * 作者:zhujie
 * 创建时间:2021/11/02 11:32
 */
public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

        UserService userService = applicationContext.getBean("userService", UserService.class);

        userService.add();
    }
}

  1. 设置优先级
    多个增强类对同一个方法进行增强,可以在在增强类上添加@Order注解可以设置优先级
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值