Srping监听Controller,Service,Dao 方法执行时间场景 http://my.oschina.net/guoenzhou/blog/738410
可能碰到依赖循环问题: http://www.mekau.com/index.php/tec/server/spring/pandy_3667.html
1.applicationContext.xml配置
beanNames根据注入实例名称来过滤拦截
interceptorNames 配置了具体拦截器实例Bean id
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="daoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="interceptorNames"> <list> <value>performanceInterceptor</value> </list> </property> <property name="beanNames"> <list> <value>*Dao</value> <value>*Controller</value> <value>*Service</value> </list> </property> </bean> <bean id="performanceInterceptor"class="com..PerformanceInstrumentInterceptor"> <property name="threshold" value="200"/> </bean> </beans> |
2.监听执行时间拦截器
拦截器类实现MethodInterceptor
threshold为超时阀值,超过这个阀值日志打印出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.interceptor; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PerformanceInstrumentInterceptor implements MethodInterceptor { private static final Logger logger = LoggerFactory .getLogger(PerformanceInstrumentInterceptor.class); private long threshold=10; public long getThreshold() { return threshold; } public void setThreshold(long threshold) { this.threshold = threshold; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { String name = invocation.getMethod().getDeclaringClass().getName() + "." + invocation.getMethod().getName(); long start = System.currentTimeMillis(); try { return invocation.proceed(); } finally { long elapseTime = System.currentTimeMillis() - start; if (elapseTime > threshold) { StringBuilder builder = new StringBuilder(); builder.append("方法").append(name); builder.append("的执行时间超过阈值").append(threshold).append("毫秒,"); builder.append("实际执行时间为").append(elapseTime).append("毫秒.\r\n"); logger.info(builder.toString()); } } } } |