首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

用xml配备的方式进行SpringAOP开发

2012-07-05 
用xml配置的方式进行SpringAOP开发?1.先定义一个简单接口:package org.pan.servicepublic interface Pers

用xml配置的方式进行SpringAOP开发

?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{@Overridepublic void delete() {System.out.println("调用delete方法");}@Overridepublic void save() {System.out.println("调用save方法");}@Overridepublic 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" /><bean id="myInterceptor" 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 {@BeforeClasspublic static void setUpBeforeClass() throws Exception {}@Test public void interceptorTest(){ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");PersonService personService=(PersonService)ctx.getBean("personService");personService.save();}}

?运行后便会在控制台输出以下信息了:

前置通知!调用save方法后置通知!

?

热点排行