题目:有一个懂得读心术的人需要完成两件事情:截听志愿者的内心感应和显示他们在想什么
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xmlns:p="http://www.springframework.org/schema/p" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 10 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 12 13 14 <bean id="magician" class="imple.Magician"/> 15 16 <aop:config> 17 <aop:aspect ref="magician"> 18 <aop:pointcut expression="execution(* inter.Thinker.thinkOfSomething(String)) and args(thoughts)" id="thingking" /> 19 <aop:before method="interceptThoughts" pointcut-ref="thingking" arg-names="thoughts"/> 20 </aop:aspect> 21 </aop:config> 26 </beans>
读心术:
1 package inter; 2 3 public interface MindReader { 4 5 void interceptThoughts(String thoughts); 6 7 String getThoughts(); 8 9 }
1 package imple; 2 3 import inter.MindReader; 4 5 public class Magician implements MindReader{ 6 7 private String thoughts; 8 9 public void interceptThoughts(String thoughts) { 10 11 System.out.println("前置Intercepting volunter‘s thoughts"); 12 this.thoughts = thoughts; 13 System.out.println(thoughts); 14 System.out.println("后置"); 15 } 16 17 public String getThoughts() { 18 return thoughts; 19 } 20 21 }
志愿者:
1 package inter; 2 3 public interface Thinker { 4 void thinkOfSomething(String thoughts); 5 }
1 package imple; 2 3 import inter.Thinker; 4 5 public class Volunteer implements Thinker{ 6 7 private String thoughts; 8 9 public void thinkOfSomething(String thoughts) { 10 this.thoughts = thoughts; 11 } 12 13 public String getThoughts(){ 14 return thoughts; 15 } 16 }
测试代码:
1 @Test 2 public void test7(){ 3 Magician magician = (Magician) ctx.getBean("magician"); 4 magician.interceptThoughts("ssss"); 5 }
运行结果:
前置Intercepting volunter‘s thoughts ssss 后置
时间: 2024-10-06 05:21:46