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

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() {

    }

    @Before("pointCut()")
    private void before(JoinPoint point) throws Exception {
}

  /* @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中使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值