用注解的方式进行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.定义一个拦截类:
package org.pan.aop;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;@Aspect//此字段说明此类为切面@SuppressWarnings("unused")public class PersonInterceptor {@Pointcut("execution (* org.pan.service.*.*(..))")private void anyMethod(){}//声明一个切点@Before("anyMethod()")public void doAccess(){System.out.println("前置通知!");}@AfterReturning("anyMethod()")public void afterDo(){System.out.println("后置通知!");}}
?4.spring配置文件:
<?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="personInterceptor" /><bean id="personService" /></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();}}
?