Sobes.tech
Middle

Why is the @Autowired annotation no longer required in Spring?

sobes.tech AI

Answer from AI

Starting from Spring 4.3, if a class has only one constructor, Spring automatically considers it for dependency injection without explicitly specifying @Autowired.

Example:

// Before Spring 4.3
@Component
public class MyService {
    private final AnotherService anotherService;

    @Autowired // Explicitly specifying @Autowired
    public MyService(AnotherService anotherService) {
        this.anotherService = anotherService;
    }
}

// With Spring 4.3 and above
@Component
public class MyService {
    private final AnotherService anotherService;

    // @Autowired is not required
    public MyService(AnotherService anotherService) {
        this.anotherService = anotherService;
    }
}

This change simplifies the code and aligns with the principle of explicit dependencies through constructors. For classes with multiple constructors or for field or setter injection, @Autowired with qualifiers/priorities is still required or should be used.

Comparison of approaches:

Approach Pros Cons
Constructor injection with @Autowired (pre 4.3) Explicit intention indication Redundancy for classes with a single constructor
Constructor injection (from 4.3) Cleaner code, follows explicit dependency principle Less obvious for beginners accustomed to explicit @Autowired
Field injection Concise syntax Hides dependencies, complicates testing
Setter injection Can be used for optional dependencies More verbose, dependencies can be null
Why is the @Autowired annotation no longer required… - sobes.tech