1.先定义一个简单接口:
package org.pan.service; public interface PersonService { public void save(); public void update(); public void delete(); }
2.实现这个接口:
package org.pan.service.impl; import org.pan.service.PersonService; public class PersonServiceBean implements PersonService{ @Override public void delete() { System.out.println("调用delete方法"); } @Override public void save() { System.out.println("调用save方法"); } @Override public void update() { System.out.println("调用update方法"); } }
3.定义一个普通的java类,这个类将作为拦截类:
package org.pan.aop; public class MyInterceptor { public void doAccessMethod(){ System.out.println("前置通知!"); } public void afterMethod(){ System.out.println("后置通知!"); } public void afterException(){ System.out.println("后置例外通知!"); } public void around(){ System.out.println("环绕通知!"); } }
4.这是spring的xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <aop:aspectj-autoproxy /> <bean id="personService" class="org.pan.service.impl.PersonServiceBean" /> <bean id="myInterceptor" class="org.pan.aop.MyInterceptor"/> <aop:config> <aop:aspect id="asp" ref="myInterceptor"> <aop:pointcut id="personPointCut" expression="execution(* org.pan.service.impl.PersonServiceBean.*(..))"/> <aop:before method="doAccessMethod" pointcut-ref="personPointCut"/> <aop:after-returning method="afterMethod" pointcut-ref="personPointCut"/> <aop:after-throwing method="afterException" pointcut-ref="personPointCut"/> </aop:aspect> </aop:config> </beans>
这就是一个简单的实例了,现在来个单元测试一下:
package junit.test; import org.junit.BeforeClass; import org.junit.Test; import org.pan.service.PersonService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringAopTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void interceptorTest(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); PersonService personService=(PersonService)ctx.getBean("personService"); personService.save(); } }
运行后便会在控制台输出以下信息了:
前置通知! 调用save方法 后置通知!