Skip to main content

Autowiring and Bean Scopes

Autowiring

When you declare that a component requires a dependency, you utilize the @Autowired annotation. Spring supports three types of dependency injection conceptually:

  1. Constructor Injection (Recommended): Spring enforces that the dependency is provided at the exact moment the object is created. This ensures the dependency cannot be null and allows fields to be marked final.
  2. Setter Injection: Spring instantiates the object first, then calls setter methods. Useful for optional dependencies.
  3. Field Injection (Deprecated): Using @Autowired directly on a private field. Heavily discouraged because it forces tight coupling to the Spring Framework and complicates unit testing without mock frameworks.
@Service
public class OrderService {
private final PaymentService paymentService;

// Standard Constructor Injection
@Autowired
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}

(Note: As of Spring 4.3, if a class only has a single constructor, you can completely omit the @Autowired annotation).

Bean Scopes

When Spring creates an instance of your class, it relies on Scopes to dictate the lifecycle of that specific instance.

You can declare a scope using the @Scope annotation.

  1. Singleton (Default): Spring creates exactly one instance of the object for the entire application. Every time a class requests the bean, Spring hands it the exact same instance in memory. This offers exceptionally fast memory usage, but means the class must be strictly "thread-safe" (stateless).
  2. Prototype: Spring creates a brand new, unique instance of the object every single time it is injected or requested. Used primarily for classes that hold temporary state.
  3. Request: Creates a new instance mapping to a single HTTP request (valid only in web contexts).
  4. Session: Creates a new instance for a user's HTTP Session.