Spring MVC AOP通过注解方式拦截Controller等实现日志管理 联系客服

发布时间 : 星期日 文章Spring MVC AOP通过注解方式拦截Controller等实现日志管理更新完毕开始阅读658cb1422f3f5727a5e9856a561252d380eb2098

* @throws Exception */

private static OperationLogger giveController(JoinPoint joinPoint) throws Exception {

Signature signature = joinPoint.getSignature();

MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod();

if (method != null) {

return method.getAnnotation(OperationLogger.class); }

return null; } }

Aspect通常用于将必要的但和业务无关的逻辑和业务逻辑分离。 Spring使用的AOP注解分为三个层次: 前提条件是在xml中放开了

@Aspect放在类头上,把这个类作为一个切面。

@Pointcut放在方法头上,定义一个可被别的方法引用的切入点表达式。 5种通知。

@Before,前置通知,放在方法头上。

@After,后置【finally】通知,放在方法头上。

@AfterReturning,后置【try】通知,放在方法头上,使用returning来引用方法返回值。 @AfterThrowing,后置【catch】通知,放在方法头上,使用throwing来引用抛出的异常。 @Around,环绕通知,放在方法头上,这个方法要决定真实的方法是否执行,而且必须有返回值。

在Maven中加入以下以依赖

xsi:schemaLocation=\http://maven.apache.org/maven-v4_0_0.xsd\ 4.0.0

com.mkyong.common spring-mvc-log4j war

1.0-SNAPSHOT

SpringMVC + Log4j

1.7

4.3.2.RELEASE 2.6.2

1.2 3.1.0 1.7.4 3.1

org.springframework spring-webmvc ${spring.version}

org.springframework spring-aop ${spring.version}

org.springframework spring-aspects ${spring.version}

org.apache.logging.log4j log4j-api ${log4j.version}

org.apache.logging.log4j log4j-core ${log4j.version}

jstl jstl

${jstl.version}

javax.servlet

javax.servlet-api ${servletapi.version} provided

log4j log4j 1.2.17

org.aspectj aspectjrt

${org.aspectj-version}

javax.inject javax.inject 1

cglib cglib

${cglib.version}

org.apache.maven.plugins

maven-compiler-plugin 3.3

${jdk.version} ${jdk.version}

在spring-*.xml中加入spring支持,打开aop功能

xmlns:context=\

xsi:schemaLocation=\ http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

\

/WEB-INF/pages/

.jsp