SpringBoot整合AOP
准备工作
创建一个springboot 2.7.2版本的新项目
建议去官网生成一个springboot项目,官网地址:https://start.spring.io/
代码编写工作
pom依赖添加AOP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
定义1个切面类,如MyAspect.java
package cn.lzh.kam.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class MyAspect {
@Pointcut( "execution(* cn.lzh.kam.web.*.*(..))" )
private void myPointCut(){
}
@Before("myPointCut()")
public void before(JoinPoint jp){
log.info("前置通知:模拟权限控制");
log.info("目标类对象:{},被增强处理的方法:{}",jp.getTarget(),jp.getSignature().getName());
}
@AfterReturning("myPointCut()")
public void afterReturning(JoinPoint jp){
log.info("后置返回通知,模拟删除临时文件");
log.info("被增强处理的方法:{}",jp.getSignature().getName());
}
@Around("myPointCut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
log.info("环绕开始:执行目标方法前,模拟开启事务");
Object obj = pjp.proceed();
log.info("环绕结束:执行目标方法后,模拟关闭事务");
return obj;
}
@AfterThrowing(value = "myPointCut()",throwing = "e")
public void except(Throwable e){
log.info("异常通知:程序执行异常:{}",e.getMessage());
}
@After("myPointCut()")
public void after(){
log.info("最终通知:模拟释放资源");
}
}
定义AOP配置类,让切面生效
AOPConfig.java代码如下
package cn.lzh.kam.aop;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration //声明一个配置类
@ComponentScan("cn.lzh.kam.aop") //自动扫描包下使用的注解
@EnableAspectJAutoProxy //开启Spring对AspectJ 的支持
public class AOPConfig {
}
启动程序进行测试


浙公网安备 33010602011771号