@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("Method is about to execute"); } }
The @Before advice in Spring AOP runs before the target method executes. It allows you to run code right before the method starts, such as logging or validation.
The @Before advice method must be void and take no arguments unless using JoinPoint or other special parameters. The annotation requires a pointcut expression.
package com.example.aspect; 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.service.UserService.*(..))") public void logBefore() { System.out.println("Before method call"); } } // UserService is annotated with @Service and methods are public.
Spring AOP requires @EnableAspectJAutoProxy in a configuration class to enable proxy-based aspects. Without it, aspects are not applied.
package com.example.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class ModifyArgAspect { @Before("execution(* com.example.service.MessageService.process(String)) && args(msg)") public void beforeProcess(JoinPoint jp, String msg) { System.out.println("Before: " + msg); msg = msg.toUpperCase(); } } package com.example.service; public class MessageService { public void process(String message) { System.out.println("Processing: " + message); } }
In Java, method arguments are passed by value. Modifying the parameter inside advice does not change the original argument passed to the target method.
If a @Before advice throws an exception, it prevents the target method from running. The exception propagates up the call stack.
