1.代理模式
public interface RealMethod {
void show();
}
public class Real implements RealMethod{
@Override
public void show() {
System.out.println("show-----");
}
}
public class Proxy implements RealMethod{
public Real real = new Real();
@Override
public void show() {
before();
real.show();
after();
}
private void after() {
System.out.println("after-----");
}
private void before() {
System.out.println("before----");
}
public static void main(String[] args) {
Proxy proxy = new Proxy(); //spring改进了创建proxy的方式,不需要每个类都去写个它对应的proxy类
proxy.show();
}
}
2.spring中cglib
public class CglibProxySpringProxyFactory implements MethodInterceptor{
<T>T createProxy(T t){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(t.getClass());
enhancer.setCallback(this);
return (T)enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
before();
Object res = methodProxy.invokeSuper(o, objects);
after();
return res;
}
private void after() {
System.out.println("-----after");
}
private void before() {
System.out.println("-----before");
}
public static void main(String[] args) {
Real real = new Real();
CglibProxySpringProxyFactory proxyFactory = new CglibProxySpringProxyFactory();
Real proxy = proxyFactory.createProxy(real);
proxy.show();
}
}
todo。jdk的proxy和cglib的比较。 有错误请指正 todo动态代理具体写