Spring Aop完整实例,按照下面说明配置和代码即可完成,因为在刚接触新东西时,最简单的就是一个可以运行的DEMO,可查了很多文章都是不全或者运行有问题,所以自己写一个。
说明:本文需要有Spring IOC基础。
参考了 http://blog.csdn.net/wangpeng047/article/details/8560694
Spring 环境搭建就不说了,可以看我其他文章里面内容,不过要使用AOP需要一个 aspectjweaver-1.6.9.jar,下载后放入项目里面。
一、XML方式
1. TestAspect:切面类
2. AServiceImpl:目标对象
3. BServiceImpl:目标对象
4. ApplicationContext:Spring配置文件
说明:这里 * com.spring.service.*.*(..)) *和com中间有一个空格。
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
/**
* @param args
*/
public static void testSpringAOP(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
AService aService = (AService)ctx.getBean("aService");
aService.fooA("zhangsan");
}
public static void main(String[] args) {
testSpringAOP();
}
}
运行结果:
log Begining method: com.aop.test.AServiceImpl.fooA
AServiceImpl.fooA(msg:zhangsan)
logEndingmethod: com.aop.test.AServiceImpl.fooA
process time: 1 ms
如果报异常:java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice
缺少包com.springsource.org.aopalliance-1.0.0.jar,下载地址 http://ebr.springsource.com/repository/app/bundle/version/download;jsessionid=BEA6BAD3421E4C82FCF33C4D8EA98867.jvm1?name=com.springsource.org.aopalliance&version=1.0.0&type=binary
二、注解(Annotation)方式
1. TestAnnotationAspect
2. ApplicationContext:Spring配置文件
注意:bean 的路径
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestMain {
/**
* @param args
*/
public static void testSpringAOP(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("config/applicationContext.xml");
AService aService = (AService)ctx.getBean("aService");
aService.fooA("zhangsan");
}
public static void main(String[] args) {
testSpringAOP();
}
}
运行测试结果:
进入方法---环绕通知
前置通知
进入方法---环绕通知
前置通知
AServiceImpl.fooA(msg:zhangsan)
退出方法---环绕通知
最终通知
后置通知
---null---
退出方法---环绕通知
最终通知
后置通知
---null---
关于切入点表达式,大家需要好好练习才能深入理解其中含义。即使看的懂,但是写起来却非常麻烦,并没有想象中那么简单。
最后,再告诉大家:
任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint类型。JoinPoint接口提供了一系列有用的方法, 比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息。
其中getSignature()返回的Signature对象可强制转换为MethodSignature,其功能非常强大,能获取包括参数名称在内的一切方法信息。