记录一下使用注解实现spring AOP的小例子。
第一步,导入相关的jar包:aspectjweaver-1.6.8.jar(提供注解org.aspectj.lang.annotation.Aspect等)、spring-aop-3.0.4.RELEASE.jar(提供自动代理创建器org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator)、aopalliance-1.0.jar(提供拦截器功能)。
第二步,配置applicationContext.xml
其中相关AOP的配置包括:
1、xmlns:aop="http://www.springframework.org/schema/aop"
2、xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" 其中XSD的版本可以在spring-aop.jar中查看
3、<aop:aspectj-autoproxy/>
4、<bean class="com.util.SecurityHandler"></bean>在spring容器中添加切面类bean
含有连接点的类UserManager
切面实现类SecurityHandler.java
测试方法:
执行结果如下:
添加前检查通过
2011-03-11 16:13:21,562 [main] DEBUG [com.service.Impl.UserManagerImpl] - add User:aaa
添加后检查通过
总结:在搭建示例过程中遇到org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException异常,提示无法获取spring-aop-3.0.xsd文件,后来发现是缺少spring-aop-3.0.4.RELEASE.jar,因为spring-aop-3.0.xsd在它里面。