- Spring 整合 aspectj 框架实现的 aop
- 在现在的开发中使用这种方案比较多.
在 spring2.0 以后它支持 jdk1.5 注解,而整合 aspectj 后可以使用 aspectj 语法,可以简化开发。
Aspect:切面 =切点+通知(多个切点与多个通知的组合)
AspectJ 它是一个第三方框架,spring 从 2.0 后可以使用 aspectJ 框架的部分语法.
AspectJ 框架它定义的通知类型有 6 种
1. 前置通知 Before 相当于 BeforeAdvice
2. 后置通知 AfterReturning 相当于 AfterReturningAdvice
3. 环绕通知 Around 相当于 MethodInterceptor
4. 抛出通知 AfterThrowing 相当于 ThrowAdvice
5. 引介通知 DeclareParents 相当于 IntroductionInterceptor
6. 最终通知 After 不管是否异常,该通知都会执行(比传统多的一个类型,传统5种)
相比 spring 的传统 AOP Advice 多了一个最终通知
- 步骤
1:指定目标对象
2增强的功能类
3:使用aop:config来声明 aop:acpect来配置切面,引入通知,设置execution表达式
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--target-->
<bean id="userService" class="com.xunjie.aspectj.UserService"></bean>
<!-- advice-->
<bean id="userServiceAdvice" class="com.xunjie.aspectj.UserServiceHelper"></bean>
<!-- 使用aop:config来声明 aop:acpect来配置切面-->
<aop:config >
<aop:aspect ref="userServiceAdvice">
<aop:before method="before" pointcut="execution(* *.add(..))"/>
</aop:aspect>
</aop:config>
</beans>