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:
- Constructor Injection (Recommended): Spring enforces that the dependency is provided at the exact moment the object is created. This ensures the dependency cannot be
nulland allows fields to be markedfinal. - Setter Injection: Spring instantiates the object first, then calls setter methods. Useful for optional dependencies.
- Field Injection (Deprecated): Using
@Autowireddirectly 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.
- 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).
- 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.
- Request: Creates a new instance mapping to a single HTTP request (valid only in web contexts).
- Session: Creates a new instance for a user's HTTP Session.