Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

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里面去,求大哥们解答


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...