使用方法拦截器MethodInterceptor和AOP统一记录Log

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记录实现

转载于:https://my.oschina.net/u/3372979/blog/1509921

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值