可能是我想得不够努力,或者答案真的难以捉摸。快速场景(尝试代码。它编译)。
考虑一个遗留接口
public interface LegacyInterfaceNoCodeAvailable{
void logInfo(String message);
}
考虑上面接口的遗留实现
public abstract class LegacyClassNoCodeAvailable implements LegacyInterfaceNoCodeAvailable{
public abstract void executeSomething();
public void rockItOldSchool(){
logInfo("bustin' chops, old-school style");
}
@Override
public void logInfo(String message){
System.out.println(message);
}
}
现在我以这个雄心勃勃的人的身份进来,为“新”系统编写了一个类,但它在“旧”框架内运行,因此我必须扩展旧基类。
public class lass SpankingShiny extends LegacyClassNoCodeAvailable{
public void executeSomething(){
rockItOldSchool();
logInfo("I'm the King around here now");
System.out.println("this new stuff rocks!!");
}
}
一切都很好,就像您期望的那样:
SpankingShiny shiny = new SpankingShiny();
shiny.executeSomething();
上面的代码产生(如预期的那样):
bustin' chops, old-school style
I'm the King around here now
this new stuff rocks!!
现在您可以看到,'System.out.println()' 忠实地打印了所需的输出。但我希望用记录器替换“System.out.println()”。
问题:
我无法让 CGLIB 代理拦截“logInfo(string)”的方法并让它通过记录器打印出我想要的消息(顺便说一下,我已经完成了日志记录配置)。该方法调用“显然”没有命中代理。
代码:
public class SpankingShinyProxy implements MethodInterceptor{
private SpankingShiny realShiny;
private final Logger logger = Logger.getLogger(SpankingShinyProxy.class);
public SpankingShinyProxy(SpankingShiny realShiny) {
super();
this.realShiny = realShiny;
}
@Override
public Object intercept(Object proxyObj, Method proxyMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
String methodName = proxyMethod.getName();
if("logInfo".equals(methodName)){
logger.info(methodParams[0]);
}
return proxyMethod.invoke(realShiny, methodParams);
}
public static SpankingShiny createProxy(SpankingShiny realObj){
Enhancer e = new Enhancer();
e.setSuperclass(realObj.getClass());
e.setCallback(new SpankingShinyProxy(realObj));
SpankingShiny proxifiedObj = (SpankingShiny) e.create();
return proxifiedObj;
}
}
主要方法:
public static void main(String... args) {
SpankingShiny shiny = new SpankingShiny();
shiny.executeSomething();
SpankingShiny shinyO = SpankingShinyProxy.createProxy(shiny);
shinyO.executeSomething();
}
上面的代码产生(不像预期的那样):
bustin' chops, old-school style
I'm the King around here now
this new stuff rocks!!
bustin' chops, old-school style
I'm the King around here now
this new stuff rocks!!
我会在哪里出错?
谢谢!