This Spring Boot app uses @Before advice to print a log message before the sayHello method runs. When you run the app, it calls sayHello which triggers the advice first.
package com.example.demo;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.GreetingService.sayHello(..))")
public void beforeSayHello() {
System.out.println("[LOG] sayHello method is about to run");
}
}
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class GreetingService {
public void sayHello(String name) {
System.out.println("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.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication implements CommandLineRunner {
private final GreetingService greetingService;
public DemoApplication(GreetingService greetingService) {
this.greetingService = greetingService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) {
greetingService.sayHello("Alice");
}
}