public class LoggingAspect implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Method execution started: " + methodInvocation.getMethod().getName());
Object result = methodInvocation.proceed();
System.out.println("Method execution completed: " + methodInvocation.getMethod().getName());
return result;
}
}
public class LoggingPointcut implements Pointcut {
public ClassFilter getClassFilter() {
return ClassFilter.TRUE;
}
public MethodMatcher getMethodMatcher() {
return MethodMatcher.TRUE;
}
}
public interface UserService {
void addUser(User user);
void updateUser(User user);
}
public class UserServiceImpl implements UserService {
public void addUser(User user) {
System.out.println("User added: " + user.getName());
}
public void updateUser(User user) {
System.out.println("User updated: " + user.getName());
}
}
public class LoggingAspect implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Method execution started: " + methodInvocation.getMethod().getName());
Object result = methodInvocation.proceed();
System.out.println("Method execution completed: " + methodInvocation.getMethod().getName());
return result;
}
}
public class Application {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
Advice loggingAspect = new LoggingAspect();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(userService.getClass());
enhancer.setCallback(loggingAspect);
UserService proxy = (UserService) enhancer.create();
proxy.addUser(new User("John Doe"));
proxy.updateUser(new User("Jane Smith"));
}
}