一、数据返回后切面注入业务值
package com.test.aspect;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* @Author Andy
* @Date 2021/9/7
*/
@Aspect
@Component
@Slf4j
public class GiftAspect {
private final static String FILED_GIFT_PROD_ID = "giftProdId";
private final static String FILED_COUPON_TYPE = "couponType";
private final static String FILED_GIFT_PRO_DTO = "giftProDto ";
@Autowired
private final ProductMapper productMapper;
@Pointcut("@annotation(com.test.aspect.annotation.AutoGiftCoupon)")
public void giftCouponPointCut() {
}
@Around("giftCouponPointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long time1 = System.currentTimeMillis();
Object result = pjp.proceed();
long time2 = System.currentTimeMillis();
log.debug("获取JSON数据 耗时:" + (time2 - time1) + "ms");
long start = System.currentTimeMillis();
this.parseCoupon(result);
long end = System.currentTimeMillis();
log.debug("解析注入JSON数据 耗时" + (end - start) + "ms");
return result;
}
/**
* 解析赠品券
*
* @param response
*/
private void parseCoupon(Object response) {
if (response instanceof ResponseEntity) {
Object result = ((ResponseEntity)response).getBody();
if (result instanceof IPage || result instanceof List) {
List<Object> list;
if (result instanceof IPage) {
list = ((IPage)result).getRecords();
} else {
list = (List<Object>)result;
}
List<JSONObject> items = new ArrayList<>();
Set<Long> set = new HashSet<>();
for (Object record : list) {
ObjectMapper mapper = new ObjectMapper();
String json = "{}";
try {
//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(record);
} catch (JsonProcessingException e) {
log.error("json解析失败" + e.getMessage(), e);
}
JSONObject item = JSONObject.parseObject(json);
/* 自定义字段注解获取数据,用来填充
for (Field field : getAllFields(record)) {
//update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
if (field.getAnnotation(Dict.class) != null) {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
String key = String.valueOf(item.get(field.getName()));
//翻译字典值对应的txt
String textValue = translateDictValue(code, text, table, key);
item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
}
}*/
Integer couponType = item.getInteger(FILED_COUPON_TYPE);
if (CouponType.C2G.value().equals(couponType)) {
set.add(item.getLong(FILED_GIFT_PROD_ID));
}
items.add(item);
}
((IPage) ((ResponseEntity) response).getBody()).setRecords(items);
Map<Long, GiftProDto> map = getGiftProDtoMap(set);
items.forEach(item -> {
Integer couponType = item.getInteger(FILED_COUPON_TYPE);
if (CouponType.C2G.value().equals(couponType)) {
Long giftProdId = item.getLong(FILED_GIFT_PROD_ID);
if (giftProdId != null) {
item.put(FILED_GIFT_PRO_DTO, map.get(giftProdId));
}
}
});
} else {
ObjectMapper mapper = new ObjectMapper();
String json = "{}";
try {
//解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
json = mapper.writeValueAsString(result);
} catch (JsonProcessingException e) {
log.error("json解析失败" + e.getMessage(), e);
}
JSONObject item = JSONObject.parseObject(json);
Integer couponType = item.getInteger(FILED_COUPON_TYPE);
if (CouponType.C2G.value().equals(couponType)) {
Long giftProdId = item.getLong(FILED_GIFT_PROD_ID);
if (giftProdId != null) {
GiftProDto giftProDto = productMapper.getGiftProInfo(giftProdId);
item.put(FILED_GIFT_PRO_DTO, giftProDto);
}
}
}
}
}
private Map<Long, GiftProDto> getGiftProDtoMap(Set<Long> set) {
Map<Long, GiftProDto> map = new HashMap<>();
set.forEach(item -> {
GiftProDto giftProDto = productMapper.getGiftProInfo(item);
map.put(item, giftProDto);
});
return map;
}
}
二、注解声明类 ,只需要在接口上加上注解即可
package com.test.aspect.annotation;
import java.lang.annotation.*;
/**
* @Author Andy
* @Date 2021/9/7
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoGiftCoupon {
/**
* 赠品券标识
*
* @return
*/
String value() default "";
}
三、利用反射获取字段值
/**
* 获取类的所有属性,包括父类
*
* @param object
* @return
*/
public static Field[] getAllFields(Object object) {
Class<?> clazz = object.getClass();
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
该博客介绍了如何使用Spring AOP(面向切面编程)来实现在返回数据中注入业务值。通过定义注解`@AutoGiftCoupon`,在方法执行前后进行拦截,解析并注入赠品券信息。在解析过程中,首先将返回对象转换为JSON,然后根据自定义字段填充数据,并调用`getGiftProDtoMap`方法获取赠品产品详情。整个过程提高了代码的可维护性和灵活性。
4404

被折叠的 条评论
为什么被折叠?



