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 />