Spring AOP切面传递参数


spring 配置文件相关配置
<aop:config>
    
     <aop:aspect ref="magician">
         
          <aop:pointcut expression="execution(* com.spring.aop.Thinker.thinkOfSomething(String)) and args(thoughts)" id="thinking"/>
         
          <aop:before pointcut-ref="thinking" method="interepetThoughts" arg-names="thoughts"/>
      aop:aspect>
aop:config>
对应的测试类
public interface MindReader {
     public void interepetThoughts(String thoughts);
     public String getThoughts();
}
@Service("magician")
public class Magician implements MindReader{
     private String thoughts;
     @Override
     public void interepetThoughts(String thoughts) {
          System.out.println("Intercepting volunteer's thoughts="+thoughts);
          this.thoughts = thoughts;
     }
     @Override
     public String getThoughts() {
          return thoughts;
     }
}
public interface Thinker {
     public void thinkOfSomething(String thoughts);
}
@Service("volunteer")
public class Volunteer implements Thinker{
     private String thoughts;
     @Override
     public void thinkOfSomething(String thoughts) {
          this.thoughts = thoughts;
     }
     public String getThoughts(){
          return thoughts;
     }
}
测试方法
public static void main(String[] args) throws Exception {
          GenericXmlApplicationContext context = new GenericXmlApplicationContext();
          context.load("com/spring/aop/applicationContext.xml");
          context.refresh();
          Volunteer volunteer = (Volunteer)context.getBean("volunteer");
          volunteer.thinkOfSomething("Queen of Hearts");
          Magician magician = (Magician)context.getBean("magician");
          System.out.println("Magician's Method "+magician.getThoughts());
     }

你可能感兴趣的:(spring)