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:
- Spring Boot scans your classes using
@ComponentScan
(included in@SpringBootApplication
). - It finds all classes annotated with
@Component
,@Service
, and@Repository
. - These classes are registered as beans in the application context.
- When you use
@Autowired
, Spring injects those beans into the places where they are needed.
π§ In Summary:
Annotation | Role |
---|---|
@Component | Generic bean to be managed by Spring |
@Service | Bean for service/business logic layer |
@Repository | Bean for data access layer |
@Autowired | Injects beans (dependencies) automatically |