Sobes.tech
Junior — Middle

What is the difference between the annotations @ComponentScan and @Component in the Spring Framework?

sobes.tech AI

Answer from AI

@Component and @ComponentScan are annotations in the Spring Framework related to component (bean) management.

  • @Component is an annotation that marks a class as a Spring component. This means Spring will create an instance of this class and register it in the application context as a bean. It is used to explicitly indicate that a class should be managed by Spring.

  • @ComponentScan is an annotation that tells Spring which packages to scan for classes with annotations like @Component, @Service, @Repository, etc. It is responsible for automatic scanning and registration of components.

Example:

@Configuration
@ComponentScan(basePackages = "com.example.app")
public class AppConfig {
    // Spring will scan the package com.example.app and register all components
}

@Component
public class MyService {
    // This class will be automatically registered as a bean
}

In summary: @Component marks a specific class as a bean, and @ComponentScan specifies where to look for such classes for automatic registration.

What is the difference between the annotations… - sobes.tech