leisure

JAVA - exceed,helloworld
随笔 - 50, 文章 - 0, 评论 - 11, 引用 - 0
数据加载中……

spring method interceptor

spring method interceptor

-author: leisure.xu

首先dao里面有find和save方法,本实例以拦截find方法为主,并改变find的返回值。

package com.leisure;

public class Dao {

     public String find() {

          System. out.println( "dao: find()");

          return "student";

     }

     public void save() {

          System. out.println( "dao: save()");

     }

}

一、新增一个DaoInterceptor,如下

package com.leisure;

import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

/**

 * class description goes here

 * @author leisure.xu

 * @version 1.0.0, 2012 -6 -29

 */

public class DaoInterceptor implements MethodInterceptor {

     @Override

     public Object invoke(MethodInvocation invocation) throws Throwable {

          String methodName = invocation.getMethod().getName();

          if( "find".equals(methodName)) {

               System. out.println( "invocation modify the return result to 'teacher'");

               return "teacher";

          }

          return invocation.proceed();

     } 

}

     DaoInterceptor实现了MethodInterceptor的invoke方法,在这里,MethodInvocation参数可以获取到getArguments等数据,至于能做什么,你懂的。

二、Dao跟DaoInterceptor还是没扯上关系,这时需要修改applicationContext.xml

     原来:

     <bean id = "dao" class= "com.leisure.Dao"/>

修改为:

          <!--

      <bean id=" dao" class="com.leiusre.Dao"/>

     -->

     <bean id ="daoInterceptor" class="com.leisure.DaoInterceptor"/>

     <bean id ="dao" class= "org.springframework.aop.framework.ProxyFactoryBean" >

          <property name ="target">

               <bean class ="com.leisure.Dao" />

          </property >

          <property name ="interceptorNames">

               <list >

                    <value >daoInterceptor </value >

               </list >

          </property >

     </bean >

三、运行看效果!

     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );

     Dao dao = context.getBean(Dao. class);

     System. out.println(dao.find());

     dao.save();

结果:

invocation modify the return result to 'teacher'

teacher

dao: save()

从结果可以看出invocation拦截了find方法,并且修改了其返回结果,而对象的find方法并没有执行到。

该实例引用到的jar包:




posted on 2012-07-11 09:14 leisure 阅读(975) 评论(0)  编辑  收藏 所属分类: java


只有注册用户登录后才能发表评论。


网站导航: