How Spring Boot Handles Dependency Injection Using Annotations?

Support this post with a reaction:

In Spring Boot, dependency injection (DI) is handled automatically through a powerful combination of annotations. Here’s how each of these works:

1. @Component

  • Marks a Java class as a Spring-managed component (bean).
  • Spring Boot automatically detects it during component scanning and adds it to the application context.
@Component
public class MyRepository {
    // Now Spring knows to manage this class as a bean
}

2. @Service (Specialized @Component)

  • Used specifically to annotate service layer classes.
  • It is functionally the same as @Component, but it adds clarity to the code structure.
@Service
public class MyService {
    // Meant for business logic, and automatically managed by Spring
}

3. @Repository (Specialized @Component)

  • Used to annotate DAO or repository layer classes.
  • Provides additional features like exception translation, turning SQL exceptions into Spring’s DataAccessException.
@Repository
public class MyDatabaseRepo {
    // For data access logic
}

4. @Autowired

  • This is the key annotation that performs the actual injection of the dependency.
  • It tells Spring to find the matching bean (by type) from the application context and inject it into the current class.
@Component
public class MyService {

    private final MyRepository myRepository;

    @Autowired  // Injects MyRepository bean into this constructor
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }
}

βœ… Note: Since Spring 4.3, if there’s only one constructor, @Autowired is optional.

πŸ” How It All Works Together:

  1. Spring Boot scans your classes using @ComponentScan (included in @SpringBootApplication).
  2. It finds all classes annotated with @Component, @Service, and @Repository.
  3. These classes are registered as beans in the application context.
  4. When you use @Autowired, Spring injects those beans into the places where they are needed.

🧠 In Summary:

AnnotationRole
@ComponentGeneric bean to be managed by Spring
@ServiceBean for service/business logic layer
@RepositoryBean for data access layer
@AutowiredInjects beans (dependencies) automatically

Leave a Comment

You must be to post a comment.

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now