JAVA Spring学习笔记------AOP项目

这里只介绍用法

AOP在我看来更像是对代码方法的一次增强

前提是不改动源代码

 

 有一个接口和实现类

接口里边的方法比较简单,只有一个输出

首先我们要导入Maven依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.3.22</version>
    </dependency>

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

就是这两个依赖

然后我们要创建一个方法增强类

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//声明为Bean  交给Spring来管理
@Component
//声明这是一个Aspect切片
@Aspect
public class AopTest {
    //说明这里是一个切入点
    //然后括号里边的字符为 你要增强的方法接口
    //原理不太清楚
    //实现类的方法也可以
    @Pointcut("execution(void com.demo.Dao.Impl.BookDaoImpl.say())")
    private void pt(){}

    //这里是说明是在方法调用前还是调用后增强
    @Before("pt()")
    public void test(){
        System.out.println(System.currentTimeMillis());
    }
}

然后我们在Spring配置类中声明一下使用了AOP技术

只需要加入一个注解

@EnableAspectJAutoProxy

如果使用AOP之后造成

NoSuchBeanDefinitionException: No qualifying bean of type

那么需要加入一个声明

@EnableAspectJAutoProxy(proxyTargetClass = true)

@Configuration
@ComponentScan("com.demo")
@Import({JdbcConfig.class, MybatisConfig.class})
//有注解开发的AOP
//@EnableAspectJAutoProxy
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringConfig {
}

这样一个基本的方法增强就实现了

测试方法

public class BookTest {
    @Test
    public void say(){
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = applicationContext.getBean(BookDaoImpl.class);
        bookDao.say();
    }
}

 AOP通知类型

@Around 环绕通知

 @Around("gt()")
    public Object aroundGt(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Before");
        Object ret =proceedingJoinPoint.proceed();

        System.out.println("After");
        return ret;
    }

    @Around("pt()")
    public void around(ProceedingJoinPoint proceedingJoinPoint){
        System.out.println("before");
        try {
            proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        System.out.println("After");


    }

与@Before和@After不同的是

我们需要知道环绕的位置在哪

所以我们要引入ProceedingJoinPoint proceedingJoinPoint

如果我们环绕的方法有返回类型

那么我们需要接受这个返回值,再返回给调用函数

我们可以利用ProceedingJoinPoint proceedingJoinPoint来得到环绕方法的很多信息

可以得到环绕的方法的参数

proceedingJoinPoint.getArgs();

如果要对参数进行修改

那么在修改玩之后应该将修改后的参数发送给proceed()方法

 

posted @ 2022-09-28 19:31  zzRh_5479  阅读(25)  评论(0编辑  收藏  举报