**
Spring AOP搭建:AOP(AspectJ)
**
一、 注解方式
1、导包
spring-aop-4.0.6.RELEASE
aspectjrt
aspectjweaver
aopalliance
spring-core
2、配置文件
<context:component-scan base-package="com...."></context:component-scan>
开启代理模式
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
3、切面类
@Aspect 标识切面类
@Component 注解模式
4、切入点表达式
切入点写在切面类方法前
save方法之前执行
@before(execution(public void com…userdao.save())“”)
save方法之后执行
@After("execution(返回类型 类完全限定名,方法)")
当save返回结果之后执行,若有异常则不执行
@AfterReturning("execution(返回类型 类完全限定名,方法)")
方法中若有异常执行
@AfterThrow("execution(返回类型 类完全限定名,方法)")
环绕业务代码(相当于1、2的集成)
@Around("execution(返回类型 类完全限定名,方法)")
around(ProceedingJoinPoint jointPoint)
sysout("begin")
jointPoint.proceed();
sysout("end")
使用pointcut后以上标签后括号参数可用pointCut()替代
@pointcut("execution(返回类型 类完全限定名,方法)")
public void pointCut(){}
XML方式
1、在容器中创建切面类
<bean id="aop" class="com.*.*.*.MyAop"></bean>
2、设置切入点
<aop:config>
<aop:pointcut expression="execution(此处添加切入对象方法) or execution(可或多个方法)" id="xxx"> 设置需切面对象
<aop:aspect ref="aop"> 设置切面类
<aop:before method="此处添加切面方法" pointcut-ref="xxx"/>
<aop:after-throwing method="此处添加切面方法" pointcut-ref="xxx"/>
<aop:after-returning method="此处添加切面方法" pointcut-ref="xxx"/>
<aop:around method="此处添加切面方法" pointcut-ref="xxx"/>
</aop:aspect>
</aop:config>
本文详细介绍Spring AOP(AspectJ)的搭建与应用,包括注解和XML两种配置方式,涵盖切面类、切入点表达式及各类通知(Before、After、AfterReturning、AfterThrowing、Around)的使用。
1413

被折叠的 条评论
为什么被折叠?



