1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.5</version> </dependency>
/** * 被代理类 */ public class Dao {
public String doThings(String metarita) { System.out.println("原材料:" + metarita); System.out.println("我是A,我在doThings"); return "成品"; } }
import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/** * 代理工厂 */ public class ProxyFactory implements MethodInterceptor {
private Object target;
public ProxyFactory(Object target) { this.target = target; }
/** * 生成代理类 * @return */ public Object getProxyInstance() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback(this); return enhancer.create(); }
@Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("干活前"); // 注意不能使用o,会死循环 Object invoke = method.invoke(this.target, objects); System.out.println("干活后");
return invoke; } }
/** * 测试main */ class Test { public static void main(String[] args) { //目标对象 Dao target = new Dao(); System.out.println(target.getClass()); //代理对象 Dao proxy = (Dao) new ProxyFactory(target).getProxyInstance(); System.out.println(proxy.getClass()); //执行代理对象方法 String things = proxy.doThings("0000000"); System.out.println(things); } }
|