Springboot使用注解实现Aop不生效

想着用redis来实现一个文章阅读数的增加功能,参考网上使用aop来增加阅读数,但是怎么都不能进入通知

切入点注解   
@Target({ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HyperLogInc {

    String description() default "";
}
切面实现
@Aspect
@Configuration
public class HyperLogAspect {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @desc aop切入点
     */
    @Pointcut("@annotation(space.springboot.community.aspect.HyperLogInc)")
    public void pointCut(){
    }

    /**
     * @desc 切入点后执行的内容,即通知,around,即切入点的方法执行前后执行通知,用joinPoint.proceed()来控制切入点方法的执行
     * @return
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        System.out.printf("aop around start");
        Object[] args = joinPoint.getArgs();
        Object questionId = args[0];
        Object obj = null;
        try {
            String ip = IPUtils.getIpAddr();
            String redisKey = "questionId_" + questionId;
            redisUtils.hAdd(redisKey,ip);
            obj = joinPoint.proceed();
            System.out.printf("redisKey:" + redisKey);
            System.out.printf(obj.toString());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
}

在service中调用

@Component
public class QuestionService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @HyperLogInc(description = "增加阅读数")
    public QuestionDto findQuestionById(Integer id) {
        Question question = questionMapper.findQuestionById(id);
        if (question == null) {
            throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
        }
        QuestionDto questionDto = new QuestionDto();
        User user = userMapper.findById(question.getCreator());
        BeanUtils.copyProperties(question, questionDto);
        questionDto.setUser(user);
        return questionDto;
    }
}

不论我是放在controller还是放在service,都没有进到这个aspect里面去,求大哥们解答

阅读 13.1k
5 个回答

感谢楼上各位大哥,突然发现是我太煞笔了,我是用idea新建了一个apsect文件,这个文件根本不是一个类,他不会被编译成class,即使我把public Aspect HyperLogAspect改成public class HyperLogAspect也不会被编译

HyperLogAspect类中@Around参数的值改成

@Around(value = "@annotation(space.springboot.community.aspect.HyperLogInc)")

这样就会去拦截你加了@HyperLogInc注解的方法了。

修改为如下试下

@Around("@annotation(pace.springboot.community.aspect.HyperLogInc) && @annotation(
hyperLogInc)")

即增加了@annotation

新手上路,请多包涵

Aop机制的实现是Spring通过被代理类所实现的接口来自动创建一个动态代理,所以被代理类需要实现一个接口。
没记错的话应该是这样。:)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题