spring aop拦截controller和service

本文介绍了如何在Spring框架中配置AOP,以拦截Controller和Service层的方法。重点在于,Controller需使用CGLIB动态代理,并在低版本Spring中明确指定。同时,AOP切面类必须与被拦截的目标类处于同一上下文环境,因此需在Spring和Spring MVC配置文件中分别进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring配置:

<context:component-scan base-package="me.zxw135136" >
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<aop:aspectj-autoproxy />

spring-mvc配置:

<context:component-scan base-package="me.zxw135136" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<aop:aspectj-autoproxy />

切面类:

@Component
@Aspect
public class LogAspect {

    @Pointcut("execution(* me.zxw135136.novelWeb.service..*(..))")
    private void servicePointCut() {}

    @Pointcut("execution(* me.zxw135136.novelWeb.controller..*(..))")
    private void controllerPointCut() {}

    @Around("servicePointCut()")
    public Object logAroundService(ProceedingJoinPoint jointPoint) throws Throwable {

        System.out.println(jointPoint+"开始");

        Object proceed = jointPoint.proceed();

        System.out.println(jointPoint+"结束");

        return proceed;
    }

    @Around("controllerPointCut()")
    public Object logAroundController(ProceedingJoinPoint jointPoint) throws Throwable {

        System.out.println(jointPoint+"开始");

        Object proceed = jointPoint.proceed();

        System.out.println(jointPoint+"结束");

        return proceed;
    }

}

需要注意的是:
1.controller需要使用cglib动态代理才可以拦截,高版本spring可以自动选择jdk或者cglib代理,在低版本中aop:aspectj-autoproxy必须加上proxy-target-class="true"才能指定使用cglib代理。
2.aop切面类必须与目标类在同一个上下文环境。因为切面类要同时切入controller和service,而我的spring上下文环境不包含controller,spring-mvc上下文环境不包含service,所以需要在spring和spring-mvc配置文件中都配置<aop:aspectj-autoproxy />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值