关于aspectj:java2个自定义注解1个工具类对小数类型字段进行四舍五入处理

java中有时候须要对返回前端的数据做对立的数据格式化,如小数类型的字段须要格式化成保留两位小数的四舍五入格局; 这里应用两个注解: 一个标注类,一个标注字段,在返回前应用工具类办法调用一次,实现此指标. 1. 类上标注的注解@RoundMarkpackage com.niewj.common.annotation;import java.lang.annotation.*;/** * 数学字段须要格式化的类标记注解 * * @author niewj * @date 2023/3/8 16:03 */@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RoundMark {}2. 字段上标注的注解@Roundpackage com.niewj.common.annotation;import java.lang.annotation.*;/** * 实体字段格式化:float/double/decimal字段四舍五入保留2位小数(默认) * * @author niewj * @date 2023/3/8 16:03 */@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Round { int value() default 2;}3. 注解的应用package com.niewj.business.model;import com.niewj.common.annotation.Round;import com.niewj.common.annotation.RoundMark;import lombok.Data;import java.math.BigDecimal;/** * 明细数据 * * @author niewj * @date 2023-02-12 */@Data@RoundMarkpublic class DataReturnToFront { /** * 商品skuid */ private Long skuId; /** * 总商品量 */ private Long count; /** * 商品均匀曝光量 */ @Round private Double avgExp; /** * 商品均匀曝光量-环比昨日 */ @Round private Double avgExpDodRatio; /** * 商品均匀曝光量-(新增) */ @Round private Double avgExpIncrement; /** * 商品[均匀曝光量]-环比昨日-新增 */ @Round private Double avgExpIncrementDodRatio; /** * 商品[均匀成交额] */ @Round private Double avgSaleAmt; /** * 商品[均匀成交额]-环比(昨日) */ @Round private Double avgSaleAmtDodRatio; /** * 商品[均匀成交额]-新增 */ @Round private Float avgSaleAmtIncrement; /** * 管控[均匀成交额]-环比(昨日)-新增 */ @Round private BigDecimal avgSaleAmtIncrementDodRatio;}4.注解的处理过程,工具类:package com.niewj.common.util;import com.niewj.common.annotation.Round;import com.niewj.common.annotation.RoundMark;import lombok.extern.slf4j.Slf4j;import org.springframework.util.CollectionUtils;import java.lang.reflect.Field;import java.math.BigDecimal;import java.math.RoundingMode;import java.util.Arrays;import java.util.List;/** * 注解工具类:用于对实体对象通过类和字段上标记注解来解决对象 */@Slf4jpublic class AnnotationUtil { /** * 遍历格式化列表List内元素对象的数字字段 * * @param targetList 待处理数据汇合 * @param <T> */ public static <T> void roundListItemFields(List<T> targetList) { if (CollectionUtils.isEmpty(targetList)) { log.info("targetList为空,不须要解决"); return; } targetList.stream().forEach(e -> { roundDecimalValues(e); }); } /** * 对小数数字格局的数据四舍五入:对类上标注了@RoundMark/字段上标注了@Round的数据进行四舍五入 * * @param target 待处理实体对象 * @param <T> */ public static <T> void roundDecimalValues(T target) { Class<? extends Object> targetClass = target.getClass(); boolean hasRoundingNumberAnno = targetClass.isAnnotationPresent(RoundMark.class); if (hasRoundingNumberAnno) { //为属性解决字段值 roundDecimalField(targetClass, target); } } /** * 对指标类中的每个字段来匹配field注解,如果匹配则进行四舍五入 * * @param targetClass 标注了Round注解的类 * @param target 类的实例对象-即须要解决的字段所在对象 * @param <T> */ private static <T> void roundDecimalField(Class<? extends Object> targetClass, T target) { Field[] fields = targetClass.getDeclaredFields(); Arrays.stream(fields).forEach(field -> { boolean hasRoundingNumberAnno = field.isAnnotationPresent(Round.class); if (hasRoundingNumberAnno) { //获取注解的值 int scale = field.getAnnotation(Round.class).value(); Object originFieldVal; Object roundedFieldVal; try { field.setAccessible(true); originFieldVal = field.get(target); if (originFieldVal instanceof Float) { BigDecimal value = new BigDecimal(String.valueOf(originFieldVal)).setScale(scale, RoundingMode.HALF_UP); roundedFieldVal = value.floatValue(); } else if (originFieldVal instanceof Double) { BigDecimal value = new BigDecimal(String.valueOf(originFieldVal)).setScale(scale, RoundingMode.HALF_UP); roundedFieldVal = value.doubleValue(); } else if (originFieldVal instanceof BigDecimal) { roundedFieldVal = new BigDecimal(String.valueOf(originFieldVal)).setScale(scale, RoundingMode.HALF_UP); } else { roundedFieldVal = originFieldVal; } field.set(target, roundedFieldVal); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); }}5.应用形式:controller端@GetMapping("/test") @ResponseBody @RecCostTime public List<DataReturnToFront> test() { log.info("======================"); DataReturnToFront detail = new DataReturnToFront(); detail.setSkuId(233230L); detail.setCount(0L); detail.setAvgExp(2220.1234566D); detail.setAvgExpDodRatio(2220.1254566D); detail.setAvgExpIncrement(-2220.1254566D); detail.setAvgExpIncrementDodRatio(-2220.1264566D); detail.setAvgSaleAmt(2220.1234566D); detail.setAvgSaleAmtDodRatio(2220.1254566D); detail.setAvgSaleAmtIncrement(2220.1254566F); detail.setAvgSaleAmtIncrementDodRatio(BigDecimal.valueOf(0.1234566D)); DataReturnToFront detail2 = new DataReturnToFront(); detail2.setSkuId(5230L); detail2.setCount(2330L); detail2.setAvgExp(20.135634566D); detail2.setAvgExpDodRatio(22.55554566D); detail2.setAvgExpIncrement(-2220.5555D); detail2.setAvgExpIncrementDodRatio(-2220.5555D); detail2.setAvgSaleAmt(2220.5555D); detail2.setAvgSaleAmtDodRatio(2220.5555D); detail2.setAvgSaleAmtIncrement(2220.5555F); detail2.setAvgSaleAmtIncrementDodRatio(BigDecimal.valueOf(0.5555D)); List list = new ArrayList(); list.add(detail); list.add(detail2); // 四舍五入格式化-批量解决 AnnotationUtil.roundListItemFields(list); // 单个解决 AnnotationUtil.roundDecimalValues(detail); return list; }roundDecimalValues是对单个对象的标注了@Round字段(前提是类上有@RoundMark标记)进行四舍五入批改字段值.roundListItemFields是对list遍历了一下.

March 8, 2023 · 2 min · jiezi

关于aspectj:使用切片注解-打印日志

注解类package com.two.elements.annontation;import java.lang.annotation.*;/** * 查看参数 * * @author * @version 1.0 * @date 2019-03-03 02:14:00 */@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface CheckParameter { /** * 接口名称 */ String apiName() default "";}代码 package com.two.elements.annontation;import com.fasterxml.jackson.databind.ObjectMapper;import com.two.elements.util.IpUtil;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.util.StopWatch;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import java.util.Objects;/** * @author * @version 2019-02-01 */@Aspect@Componentpublic class CheckParameterAspect { private static final Logger logger = LoggerFactory.getLogger(CheckParameterAspect.class); @Around("@annotation(checkParameter)") public Object checkParameter(ProceedingJoinPoint joinPoint, CheckParameter checkParameter) throws Throwable { StopWatch watch = new StopWatch(); watch.start(); HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); String apiName = checkParameter.apiName(); String method = request.getMethod(); String url = request.getRequestURL().toString(); String ip = IpUtil.getIpAddr(request); String userAgent = request.getHeader("User-Agent"); String params = ""; try { params = new ObjectMapper().writeValueAsString(joinPoint.getArgs()[0]); } catch (Exception ex) { ex.printStackTrace(); } logger.info("\n------{}------\nURL:{}\nMethod:{}\nIP:{}\nParams:{}\nUser-Agent:{}\n-------------------- 分割线 --------------------", apiName, url, method, ip, params, userAgent); Object result = joinPoint.proceed(); watch.stop(); logger.info("返回数据:{}", result); logger.info("{}耗时:{}毫秒", apiName, watch.getTotalTimeMillis()); return result; }}切片类org.aspectj.lang.annotation.Aroundorg.aspectj.lang.annotation.Aspect调用@CheckParameter(apiName = "xxx")@RequestMapping... ...

July 3, 2022 · 1 min · jiezi

AspectJ在Spring中的使用

在上一篇AspectJ的入门中,简单的介绍了下AspectJ的使用,主要是以AspectJ的example作为例子。介绍完后也留下了几个问题:1)我们在spring中并没有看到需要aspectj之类的关键词,而是使用java代码就可以了,这是如何做到的2)Spring中如何做到不使用特殊的编译器实现aop的(AspectJ如何在运行期使用)3)Spring源码中与aspectJ 相关的AjType究竟是啥?这篇文章会继续试着解决这几个问题。aspectJ的几种织入方式compile-time、post-compile 和 load-time Weavers首先了解下AspectJ的几种织入方式,分别是compile-time、post-compile 和 load-time,分别对应着编译期、后编译期、加载期织入编译期织入首先是编译期织入,上一篇博客所介绍的方式就是使用的编译期织入。很容易理解,普通的java源码+ aspectJ特殊语法的‘配置’ 文件 + aspectJ特殊的编译器,编译时候生成已织入后的.class文件,运行时直接运行即可。后编译期织入后编译期织入和编译期的不同在于,织入的是class字节码或者jar文件。这种形式,可以织入一个已经织入过一次的切面。同样这种情况也需要特殊的编译器加载期织入加载期顾名思义,是在类被加载进虚拟机之前织入,使用这种方式,须使用AspectJ agent。了解了这些概念,下面就要知道,spring是使用哪种呢?spring哪一种都不是,spring是在运行期进行的织入。Spring 如何使用AspectJAspectJ 本身是不支持运行期织入的,日常使用时候,我们经常回听说,spring 使用了aspectJ实现了aop,听起来好像spring的aop完全是依赖于aspectJ其实spring对于aop的实现是通过动态代理(jdk的动态代理或者cglib的动态代理),它只是使用了aspectJ的Annotation,并没有使用它的编译期和织入器,关于这个可以看这篇文章 ,也就是说spring并不是直接使用aspectJ实现aop的spring aop与aspectJ的区别看了很多篇博客以及源码,我对spring aop与aspectJ的理解大概是这样;1)spring aop 使用AspectJ语法的一个子集,一些method call, class member set/get 等aspectJ支持的语法它都不支持2)spring aop 底层是动态代理,所以受限于这点,有些增强就做不到,比如 调用自己的方法就无法走代理看下下面的例子:@Componentpublic class A{ public void method1(){ method2(); } public void method2(){ //… }}这个时候method2是无法被切到的,要想被切到可以通过如下奇葩的方式:@Componentpublic class A{ @Autowired private A a; public void method1(){ a.method2(); } public void method2(){ //… }}之前碰到这样的问题时,我还特别不能理解,现在想下aop的底层实现方式就很容易理解了。在之前写的jdk动态代理与cglib动态代理实现原理,我们知道了jdk动态代理是通过动态生成一个类的方式实现的代理,也就是说代理是不会修改底层类字节码的,所以可能生成的代理方法是这样的public void method1(){ //执行一段代码 a.method1() //执行一段代码}public void method2(){ //执行一段代码 a.method2() //执行一段代码}回头看a.method1()的源码,也就明白了,为啥method2()没有被切到,因为a.method1()执行的方法,最后调用的不是 代理对象.method2(),而是它自己的method2()(this.method2()) 这个方法本身没有任何改动反观aspectJ,aspectJ是在编译期修改了方法(类本身的字节码被改了),所以可以很轻松地实现调用自己的方法时候的增强。3)spring aop的代理必须依赖于bean被spring管理,所以如果项目没有使用spring,又想使用aop,那就只能使用aspectJ了(不过现在没有用spring的项目应该挺少的吧。。。)4)aspectJ由于是编译期进行的织入,性能会比spring好一点5)spring可以通过@EnableLoadTimeWeaving 开启加载期织入(只是知道这个东西,没怎么研究。。有兴趣的可以自己去研究下)6)spring aop很多概念和aspectJ是一致的AspectJ的注解在spring aop中的应用了解了spring与aspectJ的关系后,就能更清晰的了解spring 的aop了。先说明一点,虽然我介绍aspect的配置时,一直介绍的aspectJ文件配置方式,但是aspectJ本身是支持注解方式配置的。可以看官方文档,注解在aspectJ中的使用而spring 使用了aspectJ注解的一小部分(正如前面所说的,受限于jdk的动态代理,spring只支持方法级别的切面)回头看看AjType回头看看之前看到的这段源码,什么是AjType,经过aspectJ解析器解析后对类的一种描述,比如正常的方法可能是这样/* * 配置前置通知,使用在方法aspect()上注册的切入点 * 同时接受JoinPoint切入点对象,可以没有该参数 /@Before(“aspect()")public void before(JoinPoint joinPoint) { log.info(“before " + joinPoint);}在AjType中就能获取到很多其他的aspectJ所需的相关信息(除了java反射所能获取到的信息以外)/* * Return the pointcut object representing the specified pointcut declared by this type /public Pointcut getDeclaredPointcut(String name) throws NoSuchPointcutException;/* * Return the pointcut object representing the specified public pointcut */public Pointcut getPointcut(String name) throws NoSuchPointcutException;比如看着两个方法,可以获取到切入点信息。在看看PerClauseKind.SINGLETON 这里就复用了aspectJ的概念,详细可以看这篇文章最后部分总结下这篇文章回答了之前学习aspectJ时候碰到的几个问题,然后讨论了下aspectJ在spring中的应用。最大的收获是了解了spring与aspectJ 的关系,了解了两者对aop的不同实现所造成的使用上的影响。以后当遇到了spring aop相关的概念如果不理解,可以去aspectJ上去搜搜看了 。参考文章:Intro to AspectJspring 使用 load-time weavingspring aop和 aspectJ 的比较本文作者:端吉阅读原文本文为云栖社区原创内容,未经允许不得转载。 ...

November 22, 2018 · 1 min · jiezi