Sobes.tech
Junior — Middle

Why can Spring work without explicitly specifying the @Autowired annotation when injecting dependencies?

sobes.tech AI

Answer from AI

Starting from version 4.3, if a class has a single constructor, Spring automatically uses it for dependency injection without the need to explicitly specify the @Autowired annotation.

This simplifies the code and makes it cleaner. Therefore, @Autowired is needed:

  • If a class has multiple constructors — to specify which one to use.
  • For dependency injection through fields or setters.

Example:

@Component
public class MyService {
    private final Repository repo;

    // Single constructor — Spring will inject the dependency automatically
    public MyService(Repository repo) {
        this.repo = repo;
    }
}

Here, @Autowired is not needed because there is only one constructor.

Why can Spring work without explicitly specifying the… - sobes.tech