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.UserServiceImp”>
</bean>


<bean id="userInterceptor" 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值