LoginSignup
17
18

More than 5 years have passed since last update.

SpringにはStopWatchなんてクラスもある

Last updated at Posted at 2016-08-06

すごくどうでもいい話題ですが、Spring Frameworkにはorg.springframework.util.StopWatchなんてクラスもあります :blush:

StopWatch stopWatch = new StopWatch();
stopWatch.start();

// ... 処理時間を計測したい処理

stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
System.out.println(stopWatch.prettyPrint());
コンソール
949
StopWatch '': running time (millis) = 949
-----------------------------------------
ms     %     Task name
-----------------------------------------
00949  100%  

AOPなどを使って各処理の処理時間をログに出力する場合などに使えるクラスです。

@Component
@Aspect
public class ProcessingTimeLoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(ProcessingTimeLoggingAspect.class);

    @Around("@within(org.springframework.web.bind.annotation.RestController)")
    public Object logging(ProceedingJoinPoint pjp) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object returnObject;
        try {
            returnObject = pjp.proceed();
        } finally {
            stopWatch.stop();
            logger.info("{} : {} ms", pjp.getSignature(), stopWatch.getTotalTimeMillis());
        }
        return returnObject;
    }

}
コンソール
...
2016-08-07 00:05:32.215  INFO 46975 --- [o-auto-1-exec-1] eApplication$ProcessingTimeLoggingAspect : String com.example.DemoResttemplateApplication$DemoRestController.readme() : 783 ms
...

Springにはいろいろなユーティリティクラスやサポートクラスが提供されています。オレオレなクラスやメソッドを作る前にSpring Frameworkや3rdパーティ製のライブラリに該当するメソッドがないか調べてみましょう!!

17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18