springboot使用aspectJ


添加springboot-aop的starter

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
编写切面代码(先执行环绕方法->方法前->方法后->方法返回后,开启环绕方法时,异常方法无效)
@Aspect
@Component
public class AspectService {
//coder.rdf.mybatis.study.service包下的所有类的所有方法
@Before(value="execution(* coder.rdf.mybatis.study.service.*.*(..))")
public void before(JoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
String name = joinPoint.getSignature().getName();
System.out.println("方法前****切面方法**"+name+"***"+ Arrays.toString(args));
}

@After(value="execution(* coder.rdf.mybatis.study.service.*.*(..))")
public void after(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
String name = joinPoint.getSignature().getName();
System.out.println("方法后****切面方法**"+name+"***"+ Arrays.toString(args));
}
@AfterReturning(value="execution(* coder.rdf.mybatis.study.service.*.*(..))" ,returning = "result")
public void afterRunning(JoinPoint joinPoint,Object result){
Object[] args = joinPoint.getArgs();
String name = joinPoint.getSignature().getName();
System.out.println("方法反回后****切面方法**"+name+"***"+ Arrays.toString(args)+"***"+result);
}
@Around(value="execution(* coder.rdf.mybatis.study.service.*.*(..))")
public Object rounding(ProceedingJoinPoint joinPoint) throws Throwable {
long start = Time.now();
System.out.println("环绕方法开始****");
Object proceed = null;
try {
Object[] args = joinPoint.getArgs();
proceed = joinPoint.proceed(args);
} catch (Throwable throwable) {
throw new Throwable("方法调用失败");
}
System.out.println("环绕方法结束****");
long end = Time.now();
System.out.println("****方法执行时间**"+(start-end));
return proceed;
}

@AfterThrowing(value = "execution (* coder.rdf.mybatis.study.service.*.*(..))", throwing = "e")
public void throwException(JoinPoint joinPoint, Exception e) {
String methodName = joinPoint.getSignature().getName();
System.out.println("异常方法调用:" + methodName + " 异常信息" + e);
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM