在AOP方法拦截的时候,总会有一些参数的传递,我们可能希望在调用某个方法的时候,将这些方法悄悄的传递给
暗中的拦截方法,这样的功能如何实现呢,下面我们就这个参数传递的例子来进行一个案例。
首先书写一个接口,这个是暗中的拦截方法执行的接口
package com.bird.springidol;public interface MindReader { public void interceptThoughts(String thoughts); public String getThought();}
然后是他的实现类
package com.bird.springidol;public class Magician implements MindReader { private String thoughts; @Override public void interceptThoughts(String thoughts) { System.out.println("Intercepting volunteer's thoughts"); this.thoughts = thoughts; getThought(); } @Override public String getThought() { // TODO Auto-generated method stub System.out.println("daw"+thoughts); return thoughts; }}
然后下面是需要拦截的方法的接口
package com.bird.springidol;public interface Thinker { public void thinkOfSomething(String thoughts); public String getThoughts();}
然后是实现类
package com.bird.springidol;public class Volunteer implements Thinker { private String thoughts; @Override public void thinkOfSomething(String thoughts) { this.thoughts=thoughts; } public String getThoughts(){ return thoughts; }}
接着就是配置了
<aop:config> <aop:aspect ref="magician"> <aop:pointcut id="thinking" expression="execution(* com.bird.springidol.Thinker.thinkOfSomething(String)) and args(thoughts)"/> <aop:before method="interceptThoughts" pointcut-ref="thinking" arg-names="thoughts"/> </aop:aspect> </aop:config>
这个配置的意思就是,拦截这个Thinker接口的实现方法,其中的参数命名为thoughts,下面的before方法里面的
interceptThoughts方法接受一个参数,这个参数映射到thoughts这个地方,然后暗中的拦截方法就能接受到参数了。
其实感觉挺扰人的,得好好想想做做例子就会了。
我的测试例子
@Test public void test10(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Thinker ju = (Thinker) ctx.getBean("volunteer"); ju.thinkOfSomething("Queen of Hearts"); }
运行结果为
2012-5-22 12:25:05 org.springframework.context.support.AbstractApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@167d940: startup date [Tue May 22 12:25:05 CST 2012]; root of context hierarchy2012-5-22 12:25:05 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [beans.xml]2012-5-22 12:25:05 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ef137d: defining beans [org.springframework.aop.config.internalAutoProxyCreator,duke,duke1,sonnet29,poeticDuke,theStage,saxophone,guitar,kenny,hank,hank1,car1,audience,perform,magician,volunteer,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,org.springframework.aop.aspectj.AspectJPointcutAdvisor#2,org.springframework.aop.aspectj.AspectJPointcutAdvisor#3,performance,org.springframework.aop.aspectj.AspectJPointcutAdvisor#4,thinking]; root of factory hierarchyIntercepting volunteer's thoughtsdawQueen of Hearts
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow