首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring aop阻截

2012-10-06 
spring aop拦截.自定义被拦截的接口,且实现接口。代码: package demopublic interface UserService //被拦

spring aop拦截
.自定义被拦截的接口,且实现接口。
代码:

package demo;
public interface UserService //被拦截的接口
{
public void printUser(String user);
}


package demo;
public class UserServiceImp extends UserService //实现UserService接口
{
public void printUser(String user)
{
   System.out.println("printUser user:"+user);//显示user
  }
}

2 实现AOP的方法级拦截器。它可以在目标操作前后执行,拦截自定义接口的参数,或拦截接口返回的值。
代码:

package demo;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class UserInterceptor implements MethodInterceptor
//AOP方法拦截器
{

public Object invoke(MethodInvocation arg0) throws Throwable {

try {

if (arg0.getMethod().getName().equals("printUser"))
//拦截方法是否是UserService接口的printUser方法
{
                 Object[] args = arg0.getArguments();//被拦截的参数
                 System.out.println("user:"+args[0]);
                 arg0.getArguments()[0]="hello!" //修改被拦截的参数


            }

            System.out.println(arg0.getMethod().getName() + "---!");
return arg0.proceed();//运行UserService接口的printUser方法

        } catch (Exception e) {
throw e;
        }
    }

3. ApplicationContext.xml的设置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="userServiceImp" class="demo.UserInterceptor">
</bean>



<bean id="userService"
      class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces"><value>demo.UserService</value></property>

<property name="target"><ref local="userServiceImp"/></property>
<property name="interceptorNames">
<list>
<value>userInterceptor</value>
</list>
</property>
</bean>

</beans>


4.运行

package demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class DemoApp
{
public static void main(String[] args)
{
         ApplicationContext ac = new FileSystemXmlApplicationContext(
"classpath:ApplicationContext.xml");
    UserService us = (UserService) ac.getBean("userService");
     String user="zhao";

     us.printUser("zhao");

  }
}

运行结果:
[java]  user:zhao
[java]  printUser user:hello!
转自http://www.busfly.cn/csdn/post/694.html

热点排行