@ComponentScan
该注解用于扫描业务代码中(也就是当前工程的代码)注解的@Controller、@Service、@Component、@Configuration 等。
在SpringBoot 项目中,通过只需要使用@SpringBootApplication注解。该@SpringBootApplication是一个注解集合,包括了@ComponentScan,@EnableAutoConfiguration和@SpringBootConfiguration。
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}
注意 默认@ComponentScan扫描的是当前类所在的 package下的类。常见的,Main 类被@SpringBootApplication注解后,那么工程的其他 package 和类代码都在 Main 类所在 package 之下。
下面例子中,Main 类所在的 package 为 org.example,那么就会扫描org.example下的所有类。如果 Main类被写在了org.example.main包下,那么 org.example.controller 下的类就不会被扫描到了。
@EnableAutoConfiguration
用于将该工程依赖的其他 jar 包中的注解注入到当前工程。该注解会查找当前工程依赖的其他 jar包中的 spring.factories 文件。该文件中一般会配置:org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.example.spring.boot.XxxxxConfiguration。
The main difference between these annotations is that @ComponentScan scans for Spring components while @EnableAutoConfiguration is used for auto-configuring beans present in the classpath in Spring Boot applications.
参考
-Difference Between @ComponentScan and @EnableAutoConfiguration in Spring Boot
-Creating your own auto-configuration
-Difference between @SpringBootApplication and @EnableAutoConfiguration in Spring Boot