作者:xiaol | 来源:互联网 | 2022-12-02 16:32
1> Dean Xu..:
您可以使用Aspect。例如,您具有以下注释
@Target(METHOD)
@Retention(RUNTIME)
public @interface Delegate {
String value(); // this is the target method name
}
然后将Aspect组件添加到您的Spring上下文中
@Aspect // indicate the component is used for aspect
@Component
public class DelegateAspect {
@Around(value = "@annotation(anno)", argNames = "jp, anno") // aspect method who have the annotation @Delegate
public Object handle(ProceedingJoinPoint joinPoint, Delegate delegate) throws Exception {
Object obj = joinPoint.getThis(); // get the object
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); // get the origin method
Method target = obj.getClass().getMethod(delegate.value(), method.getParameterTypes()); // get the delegate method
return target.invoke(obj, joinPoint.getArgs()); // invoke the delegate method
}
}
现在您可以使用@Delegate
委托方法
@Component
public class DelegateBean {
@Delegate("b")
public void a(int i) {
System.out.println("a: " + i);
}
public void b(int i) {
System.out.println("b: " + i);
}
}
让我们测试
@Inject
public void init(DelegateBean a) {
a.a(1);
a.b(1);
}
输出是
b: 1
b: 1