SpringAOP配置与使用(示例)
1、pom.xml追加
spring-aspects
aspectjrt
为控制器以外的类织入切面
2、新建spring-aop.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="io.deolin.demoapp.service" /> <aop:aspectj-autoproxy /> <bean class="io.deolin.demoapp.aspect.ServiceAspect" /> </beans>
扫描控制层以外的包
3、新建切面
@Aspect public class ServiceAspect extends AspectCommon { Logger log = LogManager.getLogger(ServiceAspect.class); @Pointcut("execution(* io.deolin.demoapp.service.*.*(..))") public void performance() {} @Before("performance()") public void before(JoinPoint joinPoint) { log.info(getFinger(joinPoint) + " 业务开始"); } @AfterReturning("performance()") public void afterReturning(JoinPoint joinPoint) { log.info(getFinger(joinPoint) + " 业务结束"); } @AfterThrowing(value = "performance()", throwing = "e") public void afterThrowing(JoinPoint joinPoint, Throwable e) throws Throwable { log.error(getFinger(joinPoint) + " 业务异常 " + e.getClass().getSimpleName()); } }
abstract public class AspectCommon { protected String getFinger(JoinPoint joinPoint) { String className = joinPoint.getTarget().getClass().getSimpleName(); String mehtodName = joinPoint.getSignature().getName(); return className + "#" + mehtodName; } }
为控制器织入切面
4、dispatcherservlet-servlet.xml追加
<!-- 控制层AOP --> <aop:aspectj-autoproxy proxy-target-class="true" /> <bean class="io.deolin.demoapp.aspect.ControllerAspect" />
5、新建切面
@Aspect public class ControllerAspect extends AspectCommon { Logger log = LogManager.getLogger(ControllerAspect.class); @Pointcut("execution(* io.deolin.demoapp.controller.*.*(..))") public void performance() {} @Before("performance()") public void before(JoinPoint joinPoint) { log.info(getFinger(joinPoint) + " 请求开始"); } @AfterReturning("performance()") public void afterReturning(JoinPoint joinPoint) { log.info(getFinger(joinPoint) + " 请求结束"); } }