<dependency>
<groupId>org.springframework</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class MyAspect {
@Before("execution(* com.example.MyClass.myMethod(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("Before advice executed!");
}
@AfterReturning(pointcut = "execution(* com.example.MyClass.myMethod(..))", returning = "result")
public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
System.out.println("After returning advice executed! Result: " + result);
}
@Around("execution(* com.example.MyClass.myMethod(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Around advice: Before method execution");
Object result = joinPoint.proceed();
System.out.println("Around advice: After method execution");
return result;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
<bean id="myAspect" class="com.example.MyAspect"/>
<bean id="myClass" class="com.example.MyClass"/>
</beans>
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyClass myClass = (MyClass) context.getBean("myClass");
myClass.myMethod();
}
}