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

一、简介+工作流程。

简介

SpringAop实际上就是代理模式

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

工作流程

二、导入依赖

1.spring-aop包

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

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

2.aspectjweaver包

<dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
    </dependency>

三、定义接口和实现类

public interface BookDao {
    public void save();
    public void update();
}

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

@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 ...");
    }
}

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

@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的功能

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

六、自定义service层调用测试

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

猜你喜欢

转载自blog.csdn.net/m0_61395860/article/details/133132568