Loading

Quipoin Menu

Learn • Practice • Grow

spring / Example Project for AOP
interview

Q1. How would you implement logging using AOP in a Spring project?
Create an aspect class annotated with @Aspect and @Component.
Define a pointcut for all service methods, and a @Before advice to log method entry.
Example:
@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void log(JoinPoint jp) {
        System.out.println("Entering " + jp.getSignature());
    }
}
Enable AspectJ proxy in config with @EnableAspectJAutoProxy.

Q2. How do you measure method execution time using AOP?
Use Around advice to capture start and end time.
Example:
@Around("@annotation(com.example.Timed)")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = pjp.proceed();
    long elapsed = System.currentTimeMillis() - start;
    System.out.println(pjp.getSignature() + " took " + elapsed + " ms");
    return result;
}

Q3. How would you implement a simple security check using AOP?
Define a custom annotation @Secured, and use Before advice to check user role.
Example:
@Before("@annotation(secured)")
public void checkSecurity(Secured secured) {
    if(!userHasRole(secured.role())) throw new SecurityException();
}

Q4. What is needed to enable AOP in a Spring Boot project?
• Add spring-boot-starter-aop dependency.
• Spring Boot auto-configures AspectJ auto-proxy.
• You can also add @EnableAspectJAutoProxy manually if needed.
• Then define @Aspect classes as components.

Q5. How do you handle exceptions in AOP?
Use @AfterThrowing advice to catch exceptions. You can log them or perform custom handling.
For around advice, you can catch exceptions in the try-catch block around proceed().