spring aop拦截controller和service

spring配置:

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

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>

切面类:

@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配置文件中都配置

你可能感兴趣的:(spring,springmvc)