|
| 1 | +package us.codecraft.tinyioc.aop; |
| 2 | + |
| 3 | +import net.sf.cglib.proxy.Enhancer; |
| 4 | +import net.sf.cglib.proxy.MethodInterceptor; |
| 5 | +import net.sf.cglib.proxy.MethodProxy; |
| 6 | + |
| 7 | +import java.lang.reflect.Method; |
| 8 | + |
| 9 | +/** |
| 10 | + |
| 11 | + */ |
| 12 | +public class Cglib2AopProxy extends AbstractAopProxy { |
| 13 | + |
| 14 | + public Cglib2AopProxy(AdvisedSupport advised) { |
| 15 | + super(advised); |
| 16 | + } |
| 17 | + |
| 18 | + @Override |
| 19 | + public Object getProxy() { |
| 20 | + Enhancer enhancer = new Enhancer(); |
| 21 | + enhancer.setSuperclass(advised.getTargetSource().getTargetClass()); |
| 22 | + enhancer.setInterfaces(advised.getTargetSource().getInterfaces()); |
| 23 | + enhancer.setCallback(new DynamicAdvisedInterceptor(advised)); |
| 24 | + Object enhanced = enhancer.create(); |
| 25 | + return enhanced; |
| 26 | + } |
| 27 | + |
| 28 | + private static class DynamicAdvisedInterceptor implements MethodInterceptor { |
| 29 | + |
| 30 | + private AdvisedSupport advised; |
| 31 | + |
| 32 | + private org.aopalliance.intercept.MethodInterceptor delegateMethodInterceptor; |
| 33 | + |
| 34 | + private DynamicAdvisedInterceptor(AdvisedSupport advised) { |
| 35 | + this.advised = advised; |
| 36 | + this.delegateMethodInterceptor = advised.getMethodInterceptor(); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { |
| 41 | + if (advised.getMethodMatcher() == null |
| 42 | + || advised.getMethodMatcher().matches(method, advised.getTargetSource().getTargetClass())) { |
| 43 | + return delegateMethodInterceptor.invoke(new CglibMethodInvocation(advised.getTargetSource().getTarget(), method, args, proxy)); |
| 44 | + } |
| 45 | + return new CglibMethodInvocation(advised.getTargetSource().getTarget(), method, args, proxy).proceed(); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + private static class CglibMethodInvocation extends ReflectiveMethodInvocation { |
| 50 | + |
| 51 | + private final MethodProxy methodProxy; |
| 52 | + |
| 53 | + public CglibMethodInvocation(Object target, Method method, Object[] args, MethodProxy methodProxy) { |
| 54 | + super(target, method, args); |
| 55 | + this.methodProxy = methodProxy; |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public Object proceed() throws Throwable { |
| 60 | + return this.methodProxy.invoke(this.target, this.arguments); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments