AOP 学习, ProxyFactory 学习二
ProxyFactory: 拦截具有接口的类
public interface ITask {public void execute();}public class TaskImpl implements ITask {@Overridepublic void execute() {System.out.println("run code to here");}}import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;public class MessageDecorator implements MethodInterceptor{public Object invoke(MethodInvocation invocation) throws Throwable{System.out.print("hello\n");Object retVal=invocation.proceed();System.out.print("end");return retVal;}}import org.springframework.aop.framework.ProxyFactory;import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;public class test2 {public static void main(String[] args) { TaskImpl target =new TaskImpl();ProxyFactory pf=new ProxyFactory(target);//pf.setInterfaces(Class[] interfaces) 函数原型pf.setInterfaces(new Class[]{ITask.class});//通过setInterfaces()方法可以明确告知ProxyFactory,我们要对ITask接口类型进行代理。NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(); advisor.setMappedName("execute"); //切点advisor.setAdvice(new MessageDecorator()); //切面, 拦截时要执行的动作pf.addAdvisor(advisor); ITask task=(ITask)pf.getProxy();task.execute();}}public static void main(String[] args) { TaskImpl target =new TaskImpl();ProxyFactory pf=new ProxyFactory(target);NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(); advisor.setMappedName("execute"); advisor.setAdvice(new MessageDecorator());pf.addAdvisor(advisor); ITask task=(ITask)pf.getProxy();task.execute();}pf.setProxyTargetClass(true); // add this lineITask task=(ITask)pf.getProxy();//TaskImpl task=(TaskImpl)pf.getProxy(); // this line also works nowSystem.out.println(task.getClass());
class TaskImpl$$EnhancerByCGLIB$$67d0dc43hellorun code to hereend