import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackFilter;
/**
* 返回值表示使用第几个advice(Callback[]的索引)
*/
public class MyCglibCallbackFilter implements CallbackFilter{
@Override
public int accept(Method method) {
if(method.getName().equals("setName"))
return 0;
if(method.getName().equals("setSchool"))
return 0;
if(method.getName().equals("getName"))
return 1;
if(method.getName().equals("getSchool"))
return 1;
return 0;
}
}
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
//代理类
public class MyCglibIntecepter implements MethodInterceptor{
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
Object result=null;
before();
result = proxy.invokeSuper(obj, args);
after();
return result;
}
private void before(){
System.out.println("cglib前置增强");
}
private void after(){
System.out.println("cglib后置增强");
}
}
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import com.ziguan.test.Student;
import com.ziguan.test.StudentI;
public class TestCglibProxyWithFilter {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Student.class);
enhancer.setCallbackFilter(new MyCglibCallbackFilter());
Callback c1 = new MyCglibIntecepter();
Callback c2 = NoOp.INSTANCE;
Callback[] callbacks = new Callback[]{c1, c2};
enhancer.setCallbacks(callbacks);
StudentI proxyInstance = (StudentI)enhancer.create();
// proxyInstance.setName("peter");
proxyInstance.getName();
}
}
测试结果:
当调用student类的setXXX方法时执行MyCglibIntecepter增强,
当调用student类的setXXX方法时执行NoOp.INSTANCE增强,也就是没有任何操作