spring Aop实战

spring Aop实战

1.五大通知注解

  • @Before 前置通知
  • @After 后置通知
  • @AfterReturning 返回通知
  • @AfterThrowable 异常通知
  • @Around 环绕通知

在这里插入图片描述

1.1 @AfterReturning对方法返回的数据进行处理

  • 自定义注解(@ProcessMultiply相当于切入点)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ProcessMultiply {
}

  • 写切面方法
@Aspect
@Component
public class MultiplyAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(MultiplyAspect.class);

    private final MultiplyHandler multiplyHandler;

    public MultiplyAspect(MultiplyHandler multiplyHandler) {
        this.multiplyHandler = multiplyHandler;
    }

    @AfterReturning(value = "@annotation(自定义注解的完整路径)", returning = "result")
    public Object afterReturning(JoinPoint proceedingJoinPoint, Object result) throws Throwable {
        return multiplyHandler.process(result);
    }
}
@Component
public class MultiplyHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MultiplyHandler.class);
    private final MultiplyDBHandler multiplyDBHandler;
    private final MultiplyCacheHandler multiplyCacheHandler;

    public MultiplyHandler(MultiplyDBHandler multiplyDBHandler, MultiplyCacheHandler multiplyCacheHandler) {
        this.multiplyDBHandler = multiplyDBHandler;
        this.multiplyCacheHandler = multiplyCacheHandler;
    }
	/**
	*对返回的结果进行处理
	*/
    public Object process(Object result) {
        LOGGER.info("process method start");
        if (ObjectUtils.isEmpty(result)) {
            return result;
        }
        result = multiplyDBHandler.processMultiplyFromDB(result);
        return result;
    }
}
@Component
public class MultiplyDBHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MultiplyDBHandler.class);

    private final IConditionsMulRepository conditionsRepository;

    public MultiplyDBHandler(IConditionsMulRepository conditionsRepository) {
        this.conditionsRepository = conditionsRepository;
    }

    public Object processMultiplyFromDB(Object result) {
        if (result instanceof Collection) {
            long startTime = System.currentTimeMillis();
            processCollection((Collection<?>) result);
            long endTime = System.currentTimeMillis();
            LOGGER.info("translate Mul Language Collection size:" + ((Collection<?>) result).size() + ",spend time:" + (endTime - startTime) + "ms");
        } else {
            processObject(result);
        }
        return result;
    }


    /**
     * <p>集合多语言赋值</p>
     *
     * @author tjw 
     **/
    private void processCollection(Collection<?> collection) {
        if(CollectionUtils.isEmpty(collection)){
            return;
        }
        Object o = collection.stream().findFirst().orElse(null);
        if (collection instanceof Page) {
            o = ((Page<?>) collection).getContent().stream().findFirst().orElse(null);
        }
        if (Objects.isNull(o)) {
            return;
        }
        List<Field> fields = FieldUtils.getFieldsListWithAnnotation(o.getClass(), MultiplyField.class);
        List<MultiplyVO> multiplyVOList = packagingMultiplyVOList(fields, collection);
        if (CollectionUtils.isEmpty(multiplyVOList)) {
            return;
        }
        // 赋值
        for (MultiplyVO multiplyVO : multiplyVOList) {
            collection.forEach(x -> reflectToValue(multiplyVO, x));
        }
    }

    /**
     * <p>单实体多语言赋值</p>
     *
     * @author tjw  
     **/
    private void processObject(Object object) {
        List<Field> fields = FieldUtils.getFieldsListWithAnnotation(object.getClass(), MultiplyField.class);
        List<MultiplyVO> multiplyVOList = packagingMultiplyVOList(fields, object);
        if (CollectionUtils.isEmpty(multiplyVOList)) {
            return;
        }
        // 赋值
        for (MultiplyVO multiplyVO : multiplyVOList) {
            reflectToValue(multiplyVO, object);
        }
    }

    /**
     * <p>装配MultiplyVO</p>
     *
     * @author tjw 
     **/
    private List<MultiplyVO> packagingMultiplyVOList(List<Field> fields, Object object) {
        // 1.0 组装VO
        List<MultiplyVO> multiplyVOList = getMultiplyVO(fields, object);
        if (CollectionUtils.isEmpty(multiplyVOList)) {
            return multiplyVOList;
        }
        // 2.0 执行查询,重新组装VO
        multiplyVOList.forEach(mul -> mul.setTargetValueMap(conditionsRepository.getValueMapByConditions(mul.getIdentityKeyValueSet(), mul.getTargetClass(),
                mul.getTargetKey(), mul.getTargetField())));
        return multiplyVOList;
    }

    private List<MultiplyVO> getMultiplyVO(List<Field> fields, Object result) {
        List<MultiplyVO> multiplyVOList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(fields)) {
            return multiplyVOList;
        }
        for (Field field : fields) {
            MultiplyVO multiplyVO = new MultiplyVO(field, result);
            multiplyVOList.add(multiplyVO);
        }
        return multiplyVOList;
    }

    /**
     * <p>设置多语言字段值</p>
     *
     * @author tjw 
     **/
    private void reflectToValue(MultiplyVO multiplyVO, Object o) {
        if (MapUtils.isEmpty(multiplyVO.getTargetValueMap())) {
            return;
        }
        try {
            String typeName = o.getClass().getDeclaredField(multiplyVO.getIdentityKey()).getType().getSimpleName();
            String value = BeanUtils.getProperty(o, multiplyVO.getIdentityKey());
            if (Objects.isNull(value)) {
                return;
            }
            String name = "";
            switch (typeName) {
                case "Long":
                    name = String.valueOf(multiplyVO.getTargetValueMap().get(Long.valueOf(value)));
                    break;
                case "String":
                    name = String.valueOf(multiplyVO.getTargetValueMap().get(value));
                    break;
                default:
                    LOGGER.error("No support identityKey class type");
                    break;
            }
            BeanUtils.setProperty(o, multiplyVO.getIdentityField(), name);
        } catch (Exception e) {
            LOGGER.error("reflectToValue method error", e);
        }
    }

}

1.2 @Around通知处理excel导出

  • 自定义注解

/**
 * 将该注解加在请求数据的接口上:<p></p>
 *
 * 接口方法必须带有 {@link HttpServletResponse} 参数,将通过 {@link HttpServletResponse#getWriter()} 返回数据 <p></p>
 * 接口方法必须带有 {@link ExportParam} 参数:
 *  <ul>
 *      <li>通过 {@link ExportParam#fillerType} 指定导出方式</li>
 *      <li>通过 {@link ExportParam#exportType} 指定导出类型</li>
 *      <ul>
 *          <li>{@link ExportType#COLUMN} 查询导出的列</li>
 *          <li>{@link ExportType#DATA} 导出数据</li>
 *          <li>{@link ExportType#TEMPLATE} 导出模板</li>
 *      </ul>
 *      <li>通过 {@link ExportParam#ids} 传入选择导出的列</li>
 *  </ul>
 * 接口方法最好带有分页参数 {@link PageRequest},支持分页查询数据,从而避免大数据量导致内存溢出 <p></p>
 *
 * @author bojiangzhou 2018/07/25
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelExport {

    /**
     * 导出对象
     */
    Class<?> value() default Object.class;

    /**
     * 分组标识
     */
    Class<?>[] groups() default {};

    /**
     * 导入模板编码
     */
    String templateCode() default "";
    /**
     * 允许导出的最大数据量 0表示不限制
     */
    long maxDataCount() default 0L;
}

  • 写切面方法

/**
 * 拦截 {@link ExcelExport},处理导出列或导出数据
 *
 * @author tjw 2018/07/25
 */
@Aspect
// 设置切面执行的优先级,值越小越先执行
@Order(10)
public class ExcelExportAop {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExportAop.class);

    private final ExportDataHelper exportDataHelper;
    private final ExportColumnHelper exportColumnHelper;

    public ExcelExportAop(ExportDataHelper exportDataHelper, ExportColumnHelper exportColumnHelper) {
        this.exportDataHelper = exportDataHelper;
        this.exportColumnHelper = exportColumnHelper;
    }


    @Around(value = "@annotation(excelExport)")
    public Object excelExport(ProceedingJoinPoint joinPoint, ExcelExport excelExport) throws Throwable {
        HttpServletResponse response = null;
        ExportParam exportParam = null;
        // 获取切入方法的参数
        Object[] args = joinPoint.getArgs();

        for (Object arg : args) {
            if (arg instanceof HttpServletResponse) {
                response = (HttpServletResponse) arg;
            } else if (arg instanceof ExportParam) {
                exportParam = (ExportParam) arg;
            }
        }

        if (exportParam == null || exportParam.getExportType() == null || !ExportType.match(exportParam.getExportType())) {
        // 让目标方法执行
            return joinPoint.proceed();
        }

        Assert.notNull(response, "HttpServletResponse must not be null.");

        if (ExportType.COLUMN.equals(exportParam.getExportType())) {
            ExportColumn exportColumn = exportColumnHelper.getExportColumn(excelExport);
            ResponseWriter.write(response, exportColumn);
        } else {
            if (StringUtils.isBlank(excelExport.templateCode()) && CollectionUtils.isEmpty(exportParam.getIds())) {
                ExceptionResponse exceptionResponse = new ExceptionResponse("export.column.least-one");
                LOGGER.warn(exceptionResponse.getMessage());
                ResponseWriter.write(response, exceptionResponse);
                return null;
            }

            try {

                doExportByType(exportParam.getExportType(), joinPoint, excelExport, response);

            } catch (CommonException e) {
                LOGGER.warn("excel export error.", e);
                ExceptionResponse exceptionResponse = new ExceptionResponse(e.getCode());
                ResponseWriter.write(response, exceptionResponse);
            } catch (Exception e) {
                LOGGER.warn("excel export error.", e);
                ExceptionResponse exceptionResponse = new ExceptionResponse("export.error");
                exceptionResponse.setException(e.getMessage());
                ResponseWriter.write(response, exceptionResponse);
            }

        }
        return null;
    }

    private void doExportByType(ExportType type, ProceedingJoinPoint joinPoint, ExcelExport excelExport, HttpServletResponse response) throws Exception {
        if (ExportType.DATA.equals(type)) {
            exportDataHelper.exportExcel(joinPoint, excelExport, response);
        } else if (ExportType.TEMPLATE.equals(type)) {
            // TODO Export Template
            exportDataHelper.exportTemplate(joinPoint, excelExport, response);
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值