需求:查询订单要返回用户名
为了解耦,查询订单中不查询用户,使用aop自动注入用户名
注意:订单列表中的用户缓存到了内存,遍历查询很快,如果直接查数据库,则效率相对低
思路:对返回值加强(aop对返回值增强,向订单表中注入userName)
1.注解
/** * 设置属性非空的开关 * 只有方法上加上此注解,才会对Field上加上 FieldNotNull 的属性赋值 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface SetFieldSwitch { }
/** * 字段非空注解 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) //作用在字段上(告诉aop去哪个object调用哪个method,需要传什么param参数,查询的结果需要取哪一个targetField) public @interface FieldNotNull { Class beanClass(); // 需要去哪个class中调用 (userName的属性从) String method(); // 需要调用class中的哪个方法 String param(); // 调用方法的参数 String targetField(); //调用方法后需要哪个值(为了set到添加该注解的属性上) }
2:订单+用户对象
@Data public class UserOrder /*extends Order*/ { private Integer id; private Integer goodsId; private Integer userId; @FieldNotNull(beanClass = UserCache.class, method = "get", param = "userId", targetField = "realName") private String userName; //用户名 private String goodName; //物品名称 public UserOrder(Integer id, Integer userId, Integer goodId, String userName, String goodName) { this.userName = userName; this.goodName = goodName; this.setId(id); this.setUserId(userId); this.setGoodsId(goodId); } }
3:查询订单方法
@Service public class OrderService { @Autowired private OrderDao orderDao; @SetFieldSwitch // 开启aop增强(如果不开启,则FileNotNull注解不会起作用),将控制与实现分开) public List<UserOrder> listOrder() { return orderDao.listOrder(); } }
4:查询用户的方法
5:aop切面
使用AfterReturning
/** * * @param point 切点 * @param obj 返回值 * @return * @throws Throwable */ @AfterReturning(value = "setFieldValuePoint()", returning = "obj") public Object setValue(JoinPoint point, Object obj) throws Throwable { beanUtils.setFieldValueForCollection((Collection) obj); return obj; }
夜深了,未完待续.....