在pom中导入此两依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
<!--spring aspects依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
五种切入点,帮助我们增强我们的方法,比如给我们添加日志,进行访问前授权或检查之类的,我觉得用前四种就好,第五种会不会太耦合了呢?
//切面类
@Aspect
@Component //IOC容器管理
//设置 切入点 和 通知类型
//切入点表达式: execution(访问修饰符 增强方法返回类型 增强方法所在类全路径.方法名(参数))
//JoinPoint 切入点信息
public class LogAspect {
//@Before 前置通知
@Before(value = "execution(* com.atguigu.spring.aop.annoaop.*.*(..))")
public void beforeMethod(JoinPoint joinPoint)
{
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->前置通知" + methodName);
}
//@After() 后置通知,用户与前置通知类似
//返回 @AfterReturning 切入点信息 在括号中设置returning
@AfterReturning(value = "execution(* com.atguigu.spring.aop.annoaop.*.*(..))",returning = "result")
public void afterReturningMethod(JoinPoint joinPoint,Object result){ //此处Object类的属性要与returning一样
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->返回通知,方法名称: "+methodName+"返回结果,"+result);
}
//异常通知 @AfterThrowing 获取到目标方法异常信息 注解参数中多出属性throwing
@AfterThrowing(value = "execution(* com.atguigu.spring.aop.annoaop.*.*(..))",throwing = "ex")
public void beforeMethod(JoinPoint joinPoint,Throwable ex)
{
String methodName = joinPoint.getSignature().getName();
System.out.println("Logger-->异常通知" + methodName +"异常信息"+ex);
}
//
}
文章介绍了如何在POM中导入SpringAOP和SpringAspects依赖,然后展示了如何使用@Aspect注解创建切面类,以及@Before、@AfterReturning和@AfterThrowing注解来定义前置通知、返回通知和异常通知,用于增强方法,如添加日志、授权检查。
1440

被折叠的 条评论
为什么被折叠?



