MethodInterceptor属于AOP Around通知类型,Aroud通知在方法调用前后完成自定义的行为。它们负责选择继续执行连接点或通过返回它们自己的返回值或抛出异常来短路执行。
1.配置拦截器
方法拦截器(拦截Controller包中的所有被RequestMapping注解的方法)
在切入点使用自定义拦截器
<aop:config proxy-target-class="true">
<aop:pointcut id="visitRecordPointcutController" expression="execution(controller..*(..)) and
@annotation(org.springframework.web.bind.annotation.RequestMapping)"/>
<aop:advisor advice-ref="visitRecordInterceptor" pointcut-ref="visitRecordPointcutController" />
</aop:config>
2.log注解
public @interface PageVisit {
String pageType() default "1";
}
3.在Controller中需要记录log的Action上增加注解
public class WapHomeController {
@RequestMapping(value = { "/", "", "/index" })
@PageVisit()
public ModelAndView index() {
}
}
4.MethodInterceptor实现
public class VisitRecordInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object ret = invocation.proceed();
Method method = invocation.getMethod();
if (method.isAnnotationPresent(PageVisit.class)) {
PageVisit pageVisit = method.getAnnotation(PageVisit.class);
Object[] params = invocation.getArguments();
map.clear();
map.put("PageType", pageVisit.pageType());
map.put("CreateDate", DateUtil.getNow());
if (params.length > 0) {
Map param = (Map) params[0];
map.put("CategoryId", param.get("categoryId"));
}
//对数据库进行操作,记录log
}
return ret;
}
}
通过 invocation.proceed() 来对目标对象方法调用,返回一个Object对象。该方法不调用或者不返回该Object对象,则被拦截的方法不会被执行。
通过 invocation.getMethod() 获得当前被拦截的方法。
判断注解来记录Log,判断Method对象是否有指定的注解
获得注解对象的实例,通过invocation.getArguments()方法获得传入的参数,通过dao层进行数据库操作,记录log,即完成简单的log记录实现