深入浅出springboot2.x(7)spring AOP开发

本文深入讲解了AOP(面向切面编程)在Spring框架中的应用,包括如何使用@Aspect注解定义切面,以及@Before、@After、@AfterReturning和@AfterThrowing等通知注解的使用方法。同时,介绍了如何利用@Pointcut注解定义切点,以减少代码冗余,并通过一个具体的示例展示了环绕通知的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AOP开发详解

这里我们采用@Aspect注解方式开发。aop只能对方法进行拦截,所以首先要确定拦截什么方法,让它织入约定的流程中。

确定连接点

aop编程需要确定连接点(在spring中就是什么类的什么方法)。我们定义一个UserService接口,里面有一个printUser方法。
实体类User

public class User {
    private String id;
    private String name;
    private String note;
    ****   getter and setter *****
}

接口

public interface UserService {
    public void printUser(User user);
}

实现类

@Service
public class UserServiceImpl implements UserService {
    @Override
    public void printUser(User user) {
        if(user == null){
            throw new RuntimeException();
        }
        System.out.println(user.getId());
        System.out.println(user.getName());
        System.out.println(user.getNote());
    }
}

这是一个普通的接口和实现类,下面我们以printUser方法为连接点,进行aop编程。

开发切面

@Aspect
public class MyAspect {
  
    @Before("execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))")
    public void before(){
        System.out.println("before...");
    }
    @After("execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))")
    public void after(){
        System.out.println("after...");
    }
    @AfterReturning("execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))")
    public void afterRetunring(){
        System.out.println("afterRetunring...");
    }
    @AfterThrowing("execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing....");
    }
}

spring以@Aspect作为切面声明,当以@Aspect注解定义时,spring就会知道这是一个切面,我们就可以通过各类注解来定义各类的通知了。代码中的@Before、@After、@AfterReturning和@AfterThrowing等注解,是定义流程的,然后由springaop织入约定的流程中。

切面定义

在上面开发切面的时候@Before、@After、@AfterReturning和@AfterThrowing等注解中会定义一个正则式,这个正则式的作用就是定义什么时候启用aop,也就是spring会通过这个正则式去匹配对应的连接点(方法)是否启用切面编程,但是上面代码中每一个注解都重复写了同一个正则式,这显得就比较冗余了。可以改成下面这样

@Aspect
public class MyAspect {
    @Pointcut("execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))")
    private void print(){}
    @Before("print()")
    public void before(){
        System.out.println("before...");
    }
    @After("print()")
    public void after(){
        System.out.println("after...");
    }
    @AfterReturning("print()")
    public void afterRetunring(){
        System.out.println("afterRetunring...");
    }
    @AfterThrowing("print()")
    public void afterThrowing(){
        System.out.println("afterThrowing....");
    }
}

代码中使用@Pointcut来定义切点,它标注在print方法上,在后面的通知注解中使用方法名称来定义。关于正则式execution(* springbootall.springboot.spring.springaop2.UserServiceImpl.printUser(..))

  • execution表示在执行的时候拦截里面匹配的方法;
  • *表示返回任意类型的方法;
  • springbootall.springboot.spring.springaop2.UserServiceImpl指定目标对象的全限定名称;
  • printUser指定目标对象的方法;
  • (…)表示任意参数进行匹配。
    对于这个正则式,还可以使用Aspect指示器。
    |项目类型| 描述 |
    |–|--|
    | arg() | 限定连接点方法参数 |
项目类型描述
arg()限定连接点方法参数
@arg()通过连接点方法参数上的注解进行限定
execution()用于匹配连接点的执行方法
this()限制连接点匹配aop代理bean引用为指定的类型
target目标对象
@target限制目标对象的配置了指定的注解
within限制连接点匹配指定的类型
@within限制连接点带有匹配注解类型
@annotation限定带有指定注解的连接点

测试aop

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/print")
    @ResponseBody
    public User print(String id,String name,String note){
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setNote(note);
        userService.printUser(user);
        return user;
    }
}

通过@Autowired注入UserService 服务接口,然后使用它进行用户信息打印这里的UserService 实现类满足了切点的定义,因此spring aop会将其织入对应的流程中。然后配置启动文件使其运行

@SpringBootApplication
@ComponentScan
public class ChapterApplication {
    //定义切面
    @Bean(name="myAspect")
    public MyAspect initMyAspect(){
        return new MyAspect();
    }
    //启动程序
    public static void main(String[] args) {
        SpringApplication.run(ChapterApplication.class,args);
        System.out.println("启动成功");
    }
}

服务启动完成后,打开浏览器地址栏中输入请求地址:http://localhost:8080/user/print?id=1&name=36&note=3333
输出结果:
在这里插入图片描述
UserService 对象实际上是一个JDK动态代理对象,它代理了目标对象UserServiceImpl,通过这些spring会将我们定义的内容织入aop的流程中。

环绕通知

环绕通知是所有通知中最为强大的通知,强大也意味着难以控制。使用它的场景是在你需要大幅度修改原有目标对象的服务逻辑时,否则都尽量使用其他通知。环绕通知是一个取代原有目标对象方法的通知,当然它也提供了回调原有目标对象的能力。
我们在MyAspect中加入环绕通知

@Around("print()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("around before....");
        pjp.proceed();
        System.out.println("around after....");
    }

启动服务后测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值