定义Aspect
@Aspect
@Slf4j
public class myaspect {
@Pointcut("execution(* site.yalong.controller..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
System.out.println("in");
log.info("\n\n有人访问了:{}\nARGS :{}\n", request.getRequestURL().toString(), Arrays.toString(joinPoint.getArgs()));
}
}
@AfterReturning(returning = "object", pointcut = "webLog()")
public void doAfterReturning(Object object) throws Throwable {
// 处理完请求,返回内容
log.info("RESPONSE : " + object);
}
}
开启aop支持
<aop:aspectj-autoproxy proxy-target-class="true"/>
问题出现,定义的Aspect并不起作用
分析:
Spring与SpringMVC是2个不同的父子容器, @Aspect如果被spring容器加载的话,而@Controller注解的这些类的实例化以及注入却是由SpringMVC来完成。 @Aspect如果被spring容器加载的时候,可能Spring MVC容器还未初始化, Controller类还未初始化,所以无法正常织入。
解决方案: 把 aop:aspectj-autoproxy 移入springmvc配置文件中,并定义bean
<?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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!--2.静态资源处理器-->
<mvc:default-servlet-handler/>
<!--3.扫描包:controller-->
<context:component-scan base-package="site.yalong.controller"/>
<!-- <!–4.视图解析器–>-->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!-- <property name="prefix" value="/WEB-INF/jsp/"/>-->
<!-- <property name="suffix" value=".jsp"/>-->
<!-- </bean>-->
<!--开启aop,这个配置一定要配置在component-scan以后,并且让mvc注入aspect的bean-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean class="site.yalong.aspect.myaspect"/>
</beans>