Spring-Aop配置:xml配置 + 注解

本文展示了如何使用SpringAOP来实现横切逻辑,包括定义切点(@Pointcut),前置通知(@Before),后置通知(@After),异常通知(@AfterThrowing),返回通知(@AfterReturning)以及环绕通知(@Around)。例子中详细展示了如何处理方法执行前后的操作,以及事务管理。同时,文章对比了XML配置和注解配置的方式。
摘要由CSDN通过智能技术生成

1、横切逻辑类配置

@Component
@Aspect
public class LogUtil {

    @Pointcut("execution(public void deppon.service.AccountServiceImpl.transfer(java.lang.String,java.lang.String,int))")
    public void info(){

    }

    @Before("info()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("方法执行之前执行......");
        Object[] args = joinPoint.getArgs();
        for(Object arg:args){
            System.out.println(arg);
        }
        System.out.println("方法执行之前执行......");
    }

    //@After("info()")
    public void afterMethod(){
        System.out.println("方法执行之后执行......");
    }
    // @AfterThrowing("info()")
    public void exceptionMethod(){
        System.out.println("异常方法执行之后执行......");
    }
    // @AfterReturning("info()")
    public void finallyMethod(){
        System.out.println("finally执行......");
    }
    // @Around("info()")
    public Object surroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("事务开始!!!");
        Object returnValue = null;
        try{
            returnValue = joinPoint.proceed();
        } catch (Exception throwable) {
            throwable.printStackTrace();
            System.out.println("事务回滚!!!");
            throw throwable;
        }
        System.out.println("事务提交!!!");
        return returnValue;
    }
}

2-1、xml配置

<aop:aspectj-autoproxy/>

2-2、将 xml 配置替换成注解配置,在实例 bean上添加注解:@EnableAspectJAutoProxy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值