自定义注解,方法之后执行,方法出错终止注解

1.新建一个类,改为如下

/**
 * 模块如果需要参与统计使用这个注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Statistics {
}

2.写一个拦截器类

/**
 * @Author: connie
 * @Date: 2018/5/12 11:25
 */
@Aspect
@Component
public class StatisticalAspect {
    private static final Logger logger = LoggerFactory.getLogger(StatisticalAspect.class);
    @Autowired
    private CollectCountService collectCountService;

    @Pointcut("@annotation(io.bsa.annotation.Statistics)")
    public void statisticalPointCut() {

    }

  /* @Around("statisticalPointCut()")

    public Object around(ProceedingJoinPoint join) throws Throwable {
        MethodSignature signature = (MethodSignature) join.getSignature();
        Method method = signature.getMethod();
        Statistics statistics = method.getAnnotation(Statistics.class);
        if(statistics==null){
            throw  new RRException("该模块需要计入统计,请联系管理员");
        }
        //统计逻辑
      // saveInfo();
        return join.proceed();
    }*/

    @AfterReturning(pointcut="statisticalPointCut()", returning="retValue")
    private void after(JoinPoint join,Object retValue){

        R r = (R) retValue;
        Integer code = (Integer) r.get("code");
        if(code!=0){
           return;
        }

        MethodSignature signature = (MethodSignature) join.getSignature();
        Method method = signature.getMethod();
        Statistics statistics = method.getAnnotation(Statistics.class);
        if(statistics==null){
            throw  new RRException("该模块需要计入统计,请联系管理员");
        }
        //获取request对象
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String moduleCode = request.getParameter("moduleCode");
        String createTime = request.getParameter("createTime");
        Object userId = request.getAttribute("userId");
        if(userId==null||moduleCode==null||createTime==null){
            throw  new RRException("该模块需要计入统计,请联系管理员");
        }
        CollectCountEntity statistical=new CollectCountEntity();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN);
        statistical.setCreateUser(Long.valueOf(userId.toString()).intValue());
        try {
            statistical.setCreateTime(sdf.parse(createTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        statistical.setModuleCode(moduleCode);
        collectCountService.insert(statistical);
    }

}

3.Controller中使用


猜你喜欢

转载自blog.csdn.net/connie1451/article/details/80483371