在使用aspectj做aop编程的时候,发现并没有执行到定义的切面类里面,代码如下:
1、自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SmsRecord {
}
2、新建一个切面类
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class SmsRecordAspect {
/**
* 设置切点
*/
@Pointcut("@annotation(com.xxx.annotation.SmsRecord)")
public void smsPointcut() {
}
/**
* 前置处理
*/
@Before(value = "smsPointcut()")
public void doBefore(JoinPoint joinPoint) {
log.info("前置处理请求参数:{}", joinPoint);
}
/**
* 后置处理
* @param joinPoint
* @param result
*/
@AfterReturning(pointcut = "smsPointcut()", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Result result) {
log.info("后置处理请求参数:{}", joinPoint);
}
/**
* 异常处理
* @param joinPoint
* @param exception
*/
@AfterThrowing(pointcut = "smsPointcut()", throwing = "exception")
public void doAfterThrowing(JoinPoint joinPoint, Exception exception) {
log.info("异常处理请求参数:{}", joinPoint);
}
3、在需要的方法上添加自定义注解
@SmsRecord //定义注解
@Override
public Result sendVerificationCode(String phoneNum, String smsCode) {
log.info("向手机:{},发送短信验证码:{}", phoneNum, smsCode);
}
在controller调用上面的sendVerificationCode方法时,发现并没有执行切面里的前置和后置通知。
解决方法:在Application启动类上添加注解@EnableAspectJAutoProxy(proxyTargetClass = true)
@Slf4j
@SpringBootApplication
@MapperScan("com.xxx.mapper")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
log.info("==============启动完成================");
}
}
在Springboot中使用AspectJ进行AOP编程时遇到切面未生效的问题。问题表现为自定义注解和切面类定义后,Controller方法调用时未执行切面的前置和后置通知。解决方案是在Application启动类上添加@EnableAspectJAutoProxy(proxyTargetClass = true)注解,以启用AspectJ自动代理并指定目标类代理。

1万+

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



