Spring动态AOP

一、动态SpringAOP

动态 AOP 实现, AOP 框架在运行阶段对动态生成代理对象(在内存中以 JDK 动态代理,或 CGlib 动态地生成 AOP 代理类),如 SpringAOP

二、代码实现

1、引入相关依赖

<!--引入AOP依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2、被代理的类:

/**
 * 
 * @version: 1.1.0
 * @Description: 计算机类
 * @author: wsq
 * @date: 2020年6月22日上午11:53:58
 */
public class Calculator {
    public int plus(int i, int j) {
        System.out.println("加法开始啦!");
        return i + j;
    }

    public int reduce(int i, int j) {
        System.out.println("减法开始啦!");
        return i - j;
    }
}

3、容器类:

/**
 * 
 * @version: 1.1.0
 * @Description: 容器类
 * @author: wsq
 * @date: 2020年6月22日下午4:26:36
 */
@Configuration
@EnableAspectJAutoProxy
public class AOPConfig {
@Bean
public Calculator calculator() {
    return new Calculator();
}
@Bean
public LogAspects logAspects() {
    return new LogAspects();
}
}

4、代理类:

@Aspect
public class LogAspects {
/** 1)execution(* *(..)) 表示匹配所有方法 2)execution(public * com. savage.service.UserService.*(..)) 表示匹配com.savage.server.UserService中所有的公有方法 3)execution(* com.savage.server..*.*(..)) 表示匹配com.savage.server包及其子包下的所有方法 */ @Pointcut("execution(* com.example.demo.aop1.Calculator.*(..)) && args(i,j)") public void pointCut(int i, int j) { } @Before("pointCut(i,j)") public void beforeMethod(int i, int j) { System.out.println("i:" + i + "j:" + j); System.out.println("before方法执行中。。。。。。"); } @After("pointCut(i,j)") public void afterMethod(int i, int j) { System.out.println("after方法执行中。。。。。。"); } @AfterReturning("pointCut(i,j)") public void afterReturningMethod(int i, int j) { System.out.println("afterReturning方法执行中。。。。。。"); } @AfterThrowing("pointCut(i,j)") public void afterThrowingMethod(int i, int j) { System.out.println("afterThrowing方法执行中。。。。。。"); } @Around("pointCut(i,j)") public Object aroundThrowingMethod(ProceedingJoinPoint proceedingJoinPoint, int i, int j) throws Throwable { System.out.println("Around之前的方法执行中。。。。。。"); Object o = proceedingJoinPoint.proceed(); System.out.println("Around之后的方法执行中。。。。。。"); return o; } }

 

5、测试类:

@Test
public void test() {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AOPConfig.class);
    Calculator calculator = annotationConfigApplicationContext.getBean(Calculator.class);
    System.out.println(calculator.reduce(1, 10));
    annotationConfigApplicationContext.close();
}

注:

  • 如果要被代理的对象是个实现类,那么Spring会使用JDK动态代理来完成操作(Spirng默认采用JDK动态代理实现机制)。

  • 如果要被代理的对象不是个实现类那么,Spring会强制使用CGLib来实现动态代理。

 

posted @ 2020-06-22 16:37  码在江湖  阅读(305)  评论(0编辑  收藏  举报