一、添加依赖
<dependency> <groupId>org.springframework.boot </groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
二、创建service类
@Service public class UserService { public String getUserById(Integer id) { System.out.println("getUserByid.fun"); return "user"; } public void deleteUserById(Integer id) { System.out.println("deleteUserById.fun"); } }
三、创建切面
@Component @Aspect public class AopLogAspect { @Pointcut("execution(* com.kxg.springboot.service.*.*(..))") public void pc1() { } @Before(value="pc1()") public void before(JoinPoint joinPoint) { String name = joinPoint.getSignature().getName(); System.out.println(name + "方法开始执行..."); } @After(value = "pc1()") public void after(JoinPoint joinPoint) { String name = joinPoint.getSignature().getName(); System.out.println(name + "方法执行结束..."); } @AfterReturning(value="pc1()",returning = "result") public void afterReturning(JoinPoint joinPoint,Object result) { String name = joinPoint.getSignature().getName(); System.out.println(name + "方法返回值为:" + result); } @AfterThrowing(value = "pc1()",throwing = "e") public void afterThrowing(JoinPoint joinPoint,Exception e) { String name = joinPoint.getSignature().getName(); System.out.println(name + "方法抛出异常了,异常是" + e.getMessage()); } @Around("pc1()") public Object around(ProceedingJoinPoint pjp) throws Throwable{ return pjp.proceed(); } }
1. @Pointcut("execution(* com.kxg.springboot.service.*.*(..))")
PointCut定义切入点
第一个* 表示返回任意值
第二个*表示service包下的任意类
第三个*表示类中的任意方法
括号中的两个 点表示方法参数 任意
排除写法&& !execution(public * com.kxg.springboot.service.*(..))"
2.@Around 环绕通知,可以实现前置通知、后置通知、异常通知以及 返回通知的功能,目标方法进入环绕通知后,通过 调用ProceedingJoinPoint对象的proceed方法使目标方法继续执行,可以在这里修改目标参数、返回值等,并且可以在此处理目标方法的异常
四、在Controller创建接口
@RestController public class UserController { @Autowired UserService userService; @GetMapping("/getUserById") public String getUserById(Integer id) { return userService.getUserById(id); } @GetMapping("/deleteUserById") public void deleteUserById(Integer id) { userService.deleteUserById(id); } }