public class AOPInstrumenter implements MethodInterceptor{
private Logger log=Logger.getLogger(AOPInstrumenter.class);
private Enhancer enhancer=new Enhancer();
public Object getInstrumentedClass(Class clz){
enhancer.setSuperclass(clz);
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object o,Method method,Object[] args,MethodProxy proxy) throws Throwable{
log.info("调用日志方法"+method.getName());
Object result=proxy.invokeSuper(o,args);
return result;
}
}
3)我们来测试一下(AOPTest.java):
public class AOPTest{
public static void main(String[] args){
AOPInstrumenter instrumenter=new AOPInstrumenter();
StudentInfoServiceImpl studentInfo=(StudentInfoServiceImpl)instrumenter.getInstrumentedClass(StudentInfoServiceImpl.class);
studentInfo.findInfo("阿飞");
}
}
输出结果与以上相同。
CGLib中为实现以上目的,主要提供的类
1)Enhancer:setCallback(Callback) ,setSuperclass(Class) ,create()返回动态子类Object
2)MethodInterceptor必须实现的接口:intercept(Object,Method,Object[],MethodProxy)返回的是原方法调用的结果。和Proxy原理一样。