静态代理
package com.bjsxt.proxy; import com.bjsxt.service.SomeService; //静态代理类,要和目标类实现相同接口 public class ServiceProxy implements SomeService { SomeService target; public ServiceProxy() { super(); } public ServiceProxy(SomeService target) { super(); this.target = target; } public String doSome(){ return target.doSome().toUpperCase(); } }
package com.bjsxt.service; //主业务接口 public interface SomeService { String doSome(); }
package com.bjsxt.service.impl; import com.bjsxt.service.SomeService; //目标类 public class SomeServiceImpl implements SomeService { public SomeServiceImpl() { System.out.println("无参构造器执行!"); } @Override public String doSome() { return "China"; } }
package com.bjsxt.test; import com.bjsxt.proxy.ServiceProxy; import com.bjsxt.service.SomeService; import com.bjsxt.service.impl.SomeServiceImpl; public class SomeTest { public static void main(String[] args) { //定义目标对象 SomeService target = new SomeServiceImpl(); //定义目标对象的代理对象 SomeService proxy = new ServiceProxy(target); String result = proxy.doSome(); System.out.println(result); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- bean的定义:以下配置相当于SomeService service = new SomeServiceImpl(); --> <bean id="someServiceImpl" class="com.bjsxt.service.impl.SomeServiceImpl"></bean> </beans>
动态代理
分为:jdk动态代理和CGLIB动态代理
package com.bjsxt.test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import com.bjsxt.service.SomeService; import com.bjsxt.service.impl.SomeServiceImpl; public class SomeTest { public static void main(String[] args) { //定义目标对象 final SomeService target = new SomeServiceImpl(); //定义目标对象的代理对象 SomeService proxy = (SomeService) Proxy.newProxyInstance(target.getClass().getClassLoader(),//目标类的类加载器 target.getClass().getInterfaces(),//目标类实现的所有接口 new InvocationHandler() {//调用处理器 //proxy:代理对象 //method:目标方法 //args:目标方法参数 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String result = (String) method.invoke(target, args); return result.toUpperCase(); } }); String result1 = proxy.doSome(); System.out.println(result1); } }