Spring-AOP+入门案例(注解)+AOP切入点语法+AOP通知类型

一、简介+工作流程。

简介

SpringAop实际上就是代理模式

切面=切入点+连接点+通知

工作流程

二、导入依赖

1.spring-aop包

该包是在spring-context依赖下的子包,所以有context就有aop

java 复制代码
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

2.aspectjweaver包

java 复制代码
<dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>

三、定义接口和实现类

java 复制代码
public interface BookDao {
    public void save();
    public void update();
}

tip:@Repository 注解加在Dao层上,也就是与数据库操作的层上。

java 复制代码
@Repository
public class BookDaoImpl implements BookDao {

    public void save() {
        System.out.println(System.currentTimeMillis());
        System.out.println("book dao save ...");
    }

    public void update(){
        System.out.println("book dao update ...");
    }
}

四、定义通知类+制作通知+定义切入点

java 复制代码
@Component  //告诉spring要把MyAdvice 当作Bean
//设置当前类为切面类类
@Aspect //告诉spring要把MyAdvice 当作AOP,切面类
//定义通知类
public class MyAdvice {
    //设置切入点,要求配置在方法上方
    @Pointcut("execution(void com.itheima.dao.BookDao.update())")
    private void pt(){}

    //设置在切入点pt()的前面运行当前操作(前置通知)
    @Before("pt()")
    //制作共性通知
    public void method(){
        System.out.println(System.currentTimeMillis());
    }
}

由图可知,@Aspect 是告诉spring这是一个aop,@Pointcut 代表 pt()方法是一个切入点,注意py()方法只需要一个空架子 然后@Before("pt()") 代表在pt()方法之前将共性方法切入进去。

五、在spring核心配置中开启注解式aop的功能

java 复制代码
@Configuration
@ComponentScan("com.itheima")
//开启注解开发AOP功能
@EnableAspectJAutoProxy
public class SpringConfig {
}

六、自定义service层调用测试

java 复制代码
public class App {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = ctx.getBean(BookDao.class);
//        bookDao.update();
        bookDao.update();
//        System.out.println(bookDao.getClass());
    }j
}

七、切入点详解

切入点表达式语法规格:

切入点表达式书写技巧:

八、AOP通知类型

1.@After----在切入点之后

2.@Before----在切入点之前

3.@Around----在切入点周围

ProceedingJoinPoint是用来获取原方法的对象,并且返回的是原方法的返回值

4.@AfterReturning

5.@AfterThrowing

相关推荐
IT_陈寒1 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰2 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
用户8356290780512 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
小满zs2 小时前
Go语言第二章(小无相功)
后端·go
用户8356290780512 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k2 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花3 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
贰先生3 小时前
Xiuno BBS X版 用户封禁系统
后端
karry_k3 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
ServBay3 小时前
不会写代码也能建站?AI 时代,非技术创始人如何从零搭建自己的 Web 项目
后端·mcp