Lecture 36: AOP, Autowiring, Annotations & Bean Configuration Styles

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-24

Lecture 36

AOP, Autowiring, Annotations & Bean Configuration Styles

Week 9 | Unit IV: Spring Framework
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Explain Aspect-Oriented Programming (AOP) and its intent
  • Define aspect, pointcut, advice, join point, and weaving
  • Write simple @Before, @After, and @Around advice in Spring
  • Use @Autowired, @Qualifier, and @Primary for dependency resolution
  • Identify the role of Spring stereotype annotations
  • Compare XML, Java Config, and annotation-based configuration styles

The Problem AOP Solves


Some behaviours appear repeatedly across many classes — these are cross-cutting concerns.

  • Logging every method entry/exit
  • Checking security before every service method
  • Starting/committing database transactions
  • Measuring execution time for performance monitoring

Without AOP: copy-paste the same code everywhere.
With AOP: write it once and apply it everywhere with a rule.

AOP Core Terminology


Term Plain English Meaning
Aspect Module holding cross-cutting logic (e.g., LoggingAspect)
Advice The actual code that runs (e.g., logBefore())
Join Point A specific execution point (method call)
Pointcut A rule selecting which join points to target
Weaving Process of applying aspect code to target classes

flowchart LR
  A[Pointcut Rule] --> B[Matches Join Points]
  B --> C[Advice Code Executes]
  C --> D[Around Target Methods]

Spring AOP Advice Types


Advice When it Runs
@Before Before the matched method runs
@After After the method (always, even on exception)
@AfterReturning After method returns normally
@AfterThrowing After method throws an exception
@Around Wraps the method — runs before and after, can intercept return value

@Around is the most powerful advice type.

Logging Aspect Example


@Aspect                                               // #<1>
@Component
public class LoggingAspect {

  @Pointcut("execution(* com.example.service.*.*(..))")  // #<2>
  public void serviceLayer() {}

  @Before("serviceLayer()")                           // #<3>
  public void logBefore(JoinPoint jp) {
    System.out.println("Entering: " + jp.getSignature().getName());
  }

  @AfterReturning(pointcut = "serviceLayer()", returning = "result")
  public void logAfter(Object result) {               // #<4>
    System.out.println("Returned: " + result);
  }
}
  1. Marks class as an aspect
  2. Pointcut matches all methods in service package
  3. Runs before every matched method
  4. Runs after successful return; captures return value

@Around Advice


@Around("execution(* com.example.service.*.*(..))")
public Object measureTime(ProceedingJoinPoint pjp) throws Throwable {
  long start = System.currentTimeMillis();          // #<1>
  Object result = pjp.proceed();                    // #<2>
  long elapsed = System.currentTimeMillis() - start;
  System.out.println(pjp.getSignature() + " took " + elapsed + "ms");
  return result;                                    // #<3>
}
  1. Code before target method executes
  2. Proceeds to actual method — must be called
  3. Code after method — must return the result

Warning

Always call pjp.proceed() in @Around or the real method will never execute.

Autowiring with @Autowired


@Service
public class PaymentProcessor {

  // Constructor injection (preferred)
  private final PaymentGateway gateway;
  @Autowired
  public PaymentProcessor(PaymentGateway gateway) {
    this.gateway = gateway;
  }

  // Setter injection
  @Autowired
  public void setLogger(AuditLogger logger) {
    this.logger = logger;
  }
}

As of Spring 4.3+, @Autowired is optional on single-constructor classes.

@Qualifier and @Primary


@Component @Primary              // #<1>
public class HdfcGateway implements PaymentGateway { ... }

@Component
public class PaypalGateway implements PaymentGateway { ... }

@Service
public class CheckoutService {
  @Autowired
  @Qualifier("paypalGateway")    // #<2>
  private PaymentGateway gateway;
}
  1. @Primary — used when no @Qualifier is specified; acts as the default bean
  2. @Qualifier — selects a specific bean by name, overrides @Primary

Spring Stereotype Annotations


Annotation Layer Purpose
@Component Any Generic Spring-managed component
@Service Business logic Marks service layer beans
@Repository Data access Marks DAO beans; enables exception translation
@Controller Web MVC Marks Spring MVC controllers
@RestController REST API @Controller + @ResponseBody combined

All are specialisations of @Component — they all trigger component scanning.

Bean Configuration Style 1: XML


<!-- applicationContext.xml -->
<bean id="userRepo" class="com.example.UserRepositoryImpl"/>

<bean id="userService" class="com.example.UserService">
  <constructor-arg ref="userRepo"/>         <!--#<1>-->
  <property name="maxRetries" value="3"/>   <!--#<2>-->
</bean>
  1. Constructor injection via XML
  2. Property (setter) injection via XML

XML config is verbose but explicit — still found in legacy enterprise projects.

Bean Configuration Style 2: Java Config


@Configuration                               // #<1>
public class AppConfig {

  @Bean                                      // #<2>
  public UserRepository userRepository() {
    return new UserRepositoryImpl();
  }

  @Bean
  public UserService userService() {         // #<3>
    return new UserService(userRepository());
  }
}
  1. Tells Spring this class contains bean definitions
  2. Return value registered as a bean; method name = default bean ID
  3. Spring ensures singleton — calls the cached singleton, not new

Bean Configuration Style 3: Annotation-Based


@Repository                                  // #<1>
public class UserRepositoryImpl implements UserRepository { ... }

@Service                                     // #<2>
public class UserService {
  @Autowired
  private UserRepository repo;               // #<3>
}

@SpringBootApplication                       // #<4> — enables scan
public class App { ... }
  1. Auto-detected by component scan
  2. Auto-detected as service layer bean
  3. Spring injects matching bean automatically
  4. Triggers component scan from this package and below

Choosing a Configuration Style


Criteria XML Java Config Annotations
Verbosity High Medium Low
Type safety No Yes Yes
IDE support Average Excellent Excellent
Third-party beans Easy Easy Not possible
Recommended for Legacy Libraries/Infra Application beans

Modern Spring Boot projects use annotations for application classes and Java Config for infrastructure beans (DataSource, etc.).

Common Mistakes to Avoid


  • Forgetting @EnableAspectJAutoProxy in non-Boot projects
  • Calling pjp.proceed() zero or multiple times in @Around advice
  • Defining two beans of the same type without @Primary or @Qualifier
  • Applying @Component to a class Spring cannot instantiate (e.g., no default constructor)
  • Mixing XML and annotation config without understanding scan scope

AKTU Exam-Oriented Checklist


Prepare these high-probability questions:

  1. Explain AOP and its key terminology with a diagram
  2. Write a simple logging aspect using @Before and @AfterReturning
  3. Differentiate @Qualifier and @Primary
  4. List and explain Spring stereotype annotations
  5. Compare XML, Java Config, and annotation-based configuration

Summary


You now understand:

  • AOP separates cross-cutting concerns from business logic
  • Five advice types and when to use each
  • @Autowired, @Qualifier, @Primary for precise bean resolution
  • Stereotype annotations organising application layers
  • Three configuration styles and their trade-offs

Questions?

Next: Lecture 37 - Revision & Hands-on (Spring Core)