[v现象]cglib动态代理导致注解丢失问题及如何修改注解允许被继承
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Service anon = bean.getClass().getAnnotation(Service.class);
if (anon != null) {
try {
InvocationHandler h = Proxy.getInvocationHandler(anon);
//增设@Service注释全力支持承继,应付静态全权引致类上的@Service注释遗失
Field typeField = h.getClass().getDeclaredField("type");
typeField.setAccessible(true);
Field annotationTypeField = Class.class.getDeclaredField("annotationType");
annotationTypeField.setAccessible(true);
AnnotationType annotationType = (AnnotationType) annotationTypeField.get(typeField.get(h));
Field inheritedField = AnnotationType.class.getDeclaredField("inherited");
this.updateFinalModifiers(inheritedField);
inheritedField.set(annotationType, true);
// 获取 AnnotationInvocationHandler 的 memberValues 字段
Field memberValuesField = h.getClass().getDeclaredField("memberValues");
// 因为这个字段事 private final 修饰,所以要打开权限
memberValuesField.setAccessible(true);
// 获取 memberValues
Map memberValues = (Map) memberValuesField.get(h);
Service service = Stream.of(bean.getClass().getInterfaces())
.filter(iface -> iface.getAnnotation(Service.class) != null)
.collect(Collectors.toList())
.get(0)
.getAnnotation(Service.class);
memberValues.put("version", service.version());
memberValues.put("group", service.group());
} catch (Exception e) {
throw new BeanCreationException(String.format("%s %s %s %s %s"
, "修正"
, ClassUtils.getQualifiedName(bean.getClass())
, "的注释"
, ClassUtils.getQualifiedName(Service.class)
, "的 group值和version值出错")
, e);
}
}
return bean;
}