What does the @Autowired annotation do in Spring Boot?

What does the @Autowired annotation do in Spring Boot?

A) Manually inject dependencies into fields, constructors, or setters
B) Automatically inject dependencies into fields, constructors, or setters
C) Automatically create a new instance of a class
D) Mark a bean as lazy-initialized

Answer:

B) Automatically inject dependencies into fields, constructors, or setters

Explanation:

The @Autowired annotation in Spring Boot is used to automatically inject dependencies into fields, constructors, or setters. This annotation is part of the Spring Framework’s Dependency Injection (DI) mechanism, which allows Spring to automatically resolve and inject the required beans into the application context.

When you annotate a field, constructor, or setter method with @Autowired, Spring will automatically inject the appropriate bean based on the type. This reduces the need for manual wiring of dependencies and promotes a more modular and decoupled codebase:


@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    public void performOperation() {
        myRepository.save(new MyEntity());
    }
}

In this example, the @Autowired annotation automatically injects an instance of MyRepository into the MyService class. This simplifies the code by eliminating the need for manual dependency management, allowing the Spring Framework to handle the wiring of beans.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top