粗粒度,细粒度
使用代理
客户端------>代理对象----->目标对象
代理放行了,就调用目标对象的方法
静态代理(很少用),动态代理
为目标对象创建动态代理对象,Proxy类,jdk提供
InvocationHandler其实是回调
public class JDKProxyFactory implements InvocationHandler { private Object targetObject; public Object createProxyInstance(Object targetObject){ this.targetObject=targetObject; //生成的动态代理实例要实现目标代理的所有接口 return Proxy.newProxyInstance( this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin invoking...."); PersonServiceBean personService=(PersonServiceBean)this.targetObject; Object result=null; if(personService.getUser()!=null){ result=method.invoke(targetObject, args); }else{ System.out.println("你没有权限"); } System.out.println("end invoking...."); return result; } }
测试代码
@Test public void proxyTest(){ JDKProxyFactory factory=new JDKProxyFactory(); PersonService service=(PersonService) factory.createProxyInstance(new PersonServiceBean("aaa")); service.save("bbb"); }
输出:
begin invoking....
save
end invoking....
如果目标对象没有实现任何接口
使用cglib-nodep-2.1_3.jar
public class CGlibProxyFactory implements MethodInterceptor{ private Object targetObject; public Object createProxyInstance(Object targetObject){ this.targetObject=targetObject; Enhancer enhancer=new Enhancer(); enhancer.setSuperclass(this.targetObject.getClass()); enhancer.setCallback(this); return enhancer.create(); } @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { // TODO Auto-generated method stub PersonServiceBean bean=(PersonServiceBean) this.targetObject; Object result=null; if(bean.getUser()!=null){ result=methodProxy.invoke(this.targetObject, args); } return null; } }