先描述下完成功能的场景:
先查一个订单表,想要取得用户表的相关信息,但由于某些原因用户表不能进行关联查询,这个时候往往会想到冗余用户表字段,但这也会带来一个问题,就是用户表里的字段改变值后,比较但以维护(因为订单表的字段也需要同步修改)。
所以直接先查一遍订单表再查用户表,当然这样数据库性能肯定比较低。下面假设我们就要实现这个功能。
这是我们service实现这个功能的方法
public List<Order> query(){
//先查询所有订单
List<Order> orderList = orderMapper.queryOrder();
//侵入代码
//根据订单的用户id去查询用户名
for(Order order : orderList){
String customerName = userMapper.queryNameById(order.getCustomerId());
order.setCustomerName(customerName);
}
return orderList;
}
很容易发现,如果对于其他类似功能,那么我们这段类似的侵入代码要重复在多个方法内出现。
所以现在想要实现以下这么一个功能:给对象的某些字段自动去查询数据库注入值。
那么问题的关键就是
- 要为哪个类设置属性?
- 为哪些属性设置值?
- 需要借助哪个类去查询数据库?
- 借助类的哪个具体方法查询?
所以定义一个简单的注解来取得这四个值
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetValue {
/**
* 查询类的类名
* @return
*/
Class<?> className();
/**
* 查询的方法
* @return
*/
String methodName();
/**
* 借助的字段
* @return
*/
String paraNameForGet();
/**
* 设置的字段
* @return
*/
String paraNameForSet();
}
这样子在实体类中我们就可以通过使用该注解设置这些信息
public class Order {
/* 订单id */
private Integer id;
/* 下订单的用户id */
private Integer customerId;
/* 下订单的用户名 */
@SetValue(className = MUserMapper.class, methodName = "queryNameById", paraNameForGet = "customerId", paraNameForSet = "customerName")
private String customerName;
@SetValue(className = MUserMapper.class,methodName = "queryAgeById",paraNameForGet = "customerId",paraNameForSet = "customerAge")
private Integer customerAge;
。。。。。。
}
获得这些信息后,接下来就是要执行上面侵入代码的逻辑,下面通过AOP来实现,在此之前再写一个注解让AOP知道哪些方法需要被增强
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedSetFieldValue {
}
@Component
@Aspect
public class SetValueAnnotationAspect {
@Autowired
private BeanUtil beanUtil;
@Around("@annotation(com.ay.mybatis.annotion.annotation.NeedSetFieldValue)")
public Object setValueAround(ProceedingJoinPoint joinPoint){
System.out.println("-----------------环绕前置通知--------------------");
try {
Object o =joinPoint.proceed();
//返回类型是个集合
if(o instanceof Collection){
boolean result = beanUtil.setFieldValue((Collection)o);
if(!result){
System.out.println("设置Field值不成功");
}
}else{
System.out.println("返回类型不是集合");
}
System.out.println("-----------------环绕后置通知--------------------");
return o;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
增强后置的功能封装在BeanUtil中,那么接下来的关键就是通过反射取得注解的四个值,结合特定业务功能实现逻辑。
@Component
public class BeanUtil implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public boolean setFieldValue(Collection c) throws NoSuchMethodException, IllegalAccessException, InstantiationException {
//得到需要设置字段的类名
Iterator iterator = c.iterator();
Class cla =iterator.next().getClass();
Field[] fields = cla.getDeclaredFields();
for(Field m : fields) {
//得到注解
SetValue s = m.getAnnotation(SetValue.class);
if(s != null){
//查找类,接口无法实例化,通过springIOC容器取得实例!!!!!
Object o = applicationContext.getBean(s.className());
//参数类型一定要加!!! 不然没有方法进行匹配
//默认参数是空!!!!
Class cla2 = s.className();
//查找field方法
Method[] c2m = cla2.getMethods();
Method queryMethod = null;
// 无法知道要调用的参数类型,只好采用遍历
// cla2.getMethod(s.methodName(),Integer.class);
for(Method m2 : c2m){
if(m2.getName().equals(s.methodName())){
queryMethod = m2;
break;
}
}
//get方法
Method getMethod = cla.getMethod("get" + StringUtils.capitalize(s.paraNameForGet()));
//set方法
Method setMethod = null;
Method[] mcla = cla.getMethods();
for(Method m2: mcla){
if(m2.getName().equals("set" + StringUtils.capitalize(s.paraNameForSet()))){
setMethod = m2;
break;
}
}
iterator = c.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
try {
//获取值
Object getField = getMethod.invoke(object);
//查询
Object field = queryMethod.invoke(o, getField);
//设置值
setMethod.invoke(object, field);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return true;
}
}
思路就是取得查询类的实例对象,因为这边使用的是mybatis接口,无法直接实例化,所以通过容器获得实例。然后获得要反射调用的三个方法,然后invoke调用三个方法实现即可,很简单的反射逻辑。
这样写的优点主要是使得代码编写变得规范了很多。下面我们实现相同功能的service方法里就只要这样写就行了。
@NeedSetFieldValue //需要自动注入参数值
public List<Order> query(){
List<Order> orderList = orderMapper.queryOrder();
return orderList;
}
当然这里主要是想练习下手写注解以及反射的相关知识。
具体代码码云