Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

@Component and @ComponentScan are annotations in the Spring Framework, but they serve different functions:

  • @Component is an annotation that marks a class as a Spring component. This means Spring will create an instance of this class and manage it as a bean within the application context.

  • @ComponentScan is an annotation that tells Spring which packages to scan for classes annotated with @Component, @Service, @Repository, etc., to automatically register them as beans.

In simpler terms, @Component is applied to individual classes, while @ComponentScan is applied to a configuration class to specify the component scanning scope.

Example:

@Configuration
@ComponentScan(basePackages = "com.example.app")
public class AppConfig {
    // Spring will search for components in the com.example.app package
}

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