spring boot aop 記錄方法執行時間程式碼範例,springaop

來源:互聯網
上載者:User

spring boot aop 記錄方法執行時間程式碼範例,springaop

本文研究的主要是spring boot aop 記錄方法執行時間的實現代碼,具體如下。

為了效能調優,需要先統計出來每個方法的執行時間,直接在方法前後log輸出太麻煩,可以用AOP來加入時間統計

添加依賴
<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-aop</artifactId></dependency>
在application.properties中加入配置
spring.aop.auto=true

spring.aop.auto屬性預設是開啟的,也就是說只要引入了AOP依賴後,預設已經增加了@EnableAspectJAutoProxy。 切記千萬不要加入多餘的資訊,如@EnableAspectJAutoProxy!

實現具體代碼
@Component@Aspectpublic class LogAspect {private static final Log LOG = LogFactory.getLog(LogAspect.class);/**   * 定義一個切入點.   * 解釋下:   *   * ~ 第一個 * 代表任意修飾符及任意傳回值.   * ~ 第二個 * 定義在web包或者子包   * ~ 第三個 * 任意方法   * ~ .. 匹配任意數量的參數.   */@Pointcut("execution(* com.wedo.stream.service..*.*(..))")   public void logPointcut(){}@org.aspectj.lang.annotation.Around("logPointcut()")   public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{//   LOG.debug("logPointcut " + joinPoint + "\t");long start = System.currentTimeMillis();try {Object result = joinPoint.proceed();long end = System.currentTimeMillis();LOG.error("+++++around " + joinPoint + "\tUse time : " + (end - start) + " ms!");return result;}catch (Throwable e) {long end = System.currentTimeMillis();LOG.error("+++++around " + joinPoint + "\tUse time : " + (end - start) + " ms with exception : " + e.getMessage());throw e;}}}
注意問題

aop後方法不能正確傳回值

這個代理方法一定要傳回值,否則,在代碼中就沒有傳回值了。

//這樣是不對的 public void doAround(ProceedingJoinPoint joinPoint){}

Spring的文檔中這麼寫的:Spring AOP部分使用JDK動態代理或者CGLIB來為目標對象建立代理。如果被代理的目標實現了至少一個介面,則會使用JDK動態代理。所有該目標類型實現的介面都將被代理。若該目標對象沒有實現任何介面,則建立一個CGLIB代理。

預設是JDK動態代理,更改為cglib

總結

以上就是本文關於spring boot aop 記錄方法執行時間程式碼範例的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.