需要的包:
没有aspectjrt的话会找不到@AspectJ注解
除了以上两个之外,只需要导入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
代码
@Component
@Aspect
@Slf4j
@EnableAspectJAutoProxy//配置允许自动配置切面
public class LogAspectAnnotation {
@Before("execution(public com.hjf.student.entity.Card getCardById(String))")
//JoinPoint可以获取切入点方法的信息
public void before(JoinPoint joinPoint){
log.debug("aspectJ before");
}
@After("execution(public com.hjf.student.entity.Card getCardById(String))")
public void after(JoinPoint joinPoint){
log.debug("aspectJ after 最终通知");
}
//需要指定接收异常的参数名:throwing = "exception"
@AfterThrowing(pointcut = "execution(public com.hjf.student.entity.Card getCardById(String))",throwing = "exception")
public void afterThrowing(JoinPoint joinPoint,Exception exception){
log.debug("aspectJ afterThrowing");
}
//需要指定接收返回值的参数名:returning = "returnValue"
@AfterReturning(pointcut = "execution(public com.hjf.student.entity.Card getCardById(String))",returning = "returnValue")
public void afterReturning(JoinPoint joinPoint,Object returnValue){
log.debug("aspectJ afterReturning 后置通知");
}
@Around("execution(public com.hjf.student.entity.Card getCardById(String))")
public Object around(ProceedingJoinPoint pjp){
Object target=null;
try {
log.debug("aspectJ around 前置通知");
target = pjp.proceed();
log.debug("aspectJ around 后置通知");
} catch (Throwable e) {
log.debug("aspectJ around 异常通知");
} finally {
log.debug("aspectJ around 最终通知");
}
return target;
}
}
另需要配置以下两种的其中一种
- 在xml配置文件中开启
<aop:aspectj-autoproxy/>
或者
在切面方法中开启注解
@EnableAspectJAutoProxy