欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring aop小例子

程序员文章站 2022-04-09 09:14:42
...
接口类:

package com.test.TestSpring3;

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



实现类:

package com.test.TestSpring3;

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



AOP拦截器

package com.test.TestSpring3;

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;
}
}
}



测试类


package com.test.TestSpring3;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class TestInterceptor {

public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"classpath:applicationContext.xml");
// ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

UserService us = (UserService) ctx.getBean("userService");
us.printUser("shawn");

}
}


配置文件


<?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="com.test.TestSpring3.UserServiceImp" />

<bean id="userInterceptor" class="com.test.TestSpring3.UserInterceptor" />

<bean id="userService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 代理接口 -->
<property name="proxyInterfaces">
<value>com.test.TestSpring3.UserService</value>
</property>
<!-- 目标实现类 -->
<property name="target">
<ref local="userServiceImp" />
</property>
<!-- 拦截器 -->
<property name="interceptorNames">
<list>
<value>userInterceptor</value>
</list>
</property>
</bean>

</beans>


输出:
user:shawn
printUser---!
printUser user:hello!