通常MVC各層執行時間和效率和咱們很是關注,經過spring方法攔截器能夠實現該場景spring
beanNames根據注入實例名稱來過濾攔截app
interceptorNames 配置了具體攔截器實例Bean idide
<?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>
攔截器類實現MethodInterceptorui
threshold爲超時閥值,超過這個閥值日誌打印出來this
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()); } } } }