This Spring Boot app uses AOP to measure how long the greet method takes. The aspect prints the time, and the main app prints the greeting.
package com.example.demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimingAspect {
@Around("execution(* com.example.demo.MyService.*(..))")
public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long duration = System.currentTimeMillis() - start;
System.out.println(joinPoint.getSignature() + " took " + duration + " ms");
return result;
}
}
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String greet(String name) {
try {
Thread.sleep(100); // simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Hello, " + name;
}
}
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.example.demo")
public class DemoApplication implements CommandLineRunner {
private final MyService myService;
public DemoApplication(MyService myService) {
this.myService = myService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
String message = myService.greet("World");
System.out.println(message);
}
}