1、xml版配置aop
1.1 配置前后置通知
<!-- 配置自定义事物类 -->
<bean id="txManage" class="cn.itsource._03_aopxml.TxManage"/>
<!--配置aop-->
<aop:config>
<!--配置切点(这里面就是需要进行添加自定义代码的地方)-->
<aop:pointcut id="txAop" expression="execution(* cn.itsource._03_aopxml.service.I*Service.*(..))"/>
<!--配置切面(里面包含需要执行的自定义代码)-->
<aop:aspect ref="txManage">
<!--在这个切点(地方),执行这个事物类里的begin方法-->
<aop:before method="begin" pointcut-ref="txAop"/>
<!--后置通知-->
<aop:after-returning method="commit" pointcut-ref="txAop"/>
<!--异常通知-->
<aop:after-throwing method="rollback" pointcut-ref="txAop" throwing="e"/>
<!--最终通知-->
<aop:after method="close" pointcut-ref="txAop"/>
<!--环绕通知-->
<!--<aop:around method="around" pointcut-ref="txAop"/>-->
</aop:aspect>
</aop:config>
1.2 配置环绕通知(里面就包含前后置通知)
<bean id="txManage" class="cn.itsource._03_aopxml.TxManage"/>
<!--配置aop-->
<aop:config>
<!--配置切点-->
<aop:pointcut id="txAop" expression="execution(* cn.itsource._03_aopxml.service.I*Service.*(..))"/>
<!--配置切面-->
<aop:aspect ref="txManage">
<!--环绕通知-->
<aop:around method="around" pointcut-ref="txAop"/>
</aop:aspect>
</aop:config>
=====================================
public static void around(ProceedingJoinPoint joinPoint){
try {
begin();
joinPoint.proceed();
commit();
} catch (Throwable e) {
e.printStackTrace();
rollback(e);
} finally {
close();
}
}
2、注解配置aop
2.1 前后置通知
@Component
@Aspect
public class TxManage {
@Pointcut("execution(* cn.itsource._04_aopanno.service.I*Service.*(..))")
public static void pointcut(){
}
@Before("pointcut()")
public static void begin(){
System.out.println("前");
}
@AfterReturning("pointcut()")
public static void commit(){
System.out.println("后");
}
@AfterThrowing(value = "pointcut()",throwing = "e")
public static void rollback(Throwable e){
System.out.println("异常,原因:"+e.getMessage());
}
@After("pointcut()")
public static void close(){
System.out.println("最终");
}
}
2.2 环绕通知
@Component
@Aspect
public class TxManage {
@Pointcut("execution(* cn.itsource._04_aopanno.service.I*Service.*(..))")
public static void pointcut(){
}
public static void begin(){
System.out.println("前");
}
public static void commit(){
System.out.println("后");
}
public static void rollback(Throwable e){
System.out.println("异常,原因:"+e.getMessage());
}
public static void close(){
System.out.println("最终");
}
@Around("pointcut()")
public static void around(ProceedingJoinPoint joinPoint){
try {
begin();
joinPoint.proceed();
commit();
} catch (Throwable e) {
e.printStackTrace();
rollback(e);
} finally {
close();
}
}
}