Using @Timed Annotation in SpringBoot for Automatic Request Time Statistics
The article explains how the SpringBoot @Timed annotation can automatically record method execution times, replacing verbose manual timing code, and demonstrates basic and advanced usages with custom metric names and tags to simplify performance monitoring in backend development.
In SpringBoot development, the @Timed annotation can automatically record the execution time of controller methods, eliminating the need for repetitive manual timing code.
Traditional manual timing requires recording a start timestamp, executing the business logic, recording an end timestamp, calculating the duration, and logging it, which leads to verbose and duplicated code.
public String getUserInfo(String userId) {
long startTime = System.currentTimeMillis();
// get user info
String result = userService.getUserById(userId);
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
logger.info("Execution time for getUserInfo: " + executionTime + " ms");
return result;
}By adding the @Timed annotation, Spring automatically records the method’s execution time and logs it, removing the need for the manual code above.
@Timed
@GetMapping("/user/{userId}")
public String getUserInfo(@PathVariable String userId) {
return userService.getUserById(userId);
}The annotation also supports advanced features such as custom metric names and extra tags, which help differentiate metrics for various request types.
@Timed(value = "user.getInfo", extraTags = {"type", "profile"})
@GetMapping("/user/{userId}")
public String getUserInfo(@PathVariable String userId) {
return userService.getUserById(userId);
}In a real e‑commerce project, many endpoints were annotated with @Timed , for example:
@Timed
@GetMapping("/products")
public List
getProducts() {
return productService.getAllProducts();
}This approach simplifies time statistics, improves development efficiency, enhances code maintainability, and provides flexible tagging for detailed performance analysis.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.