关于注解@ComponentScan
关于注解@ComponentScan
ComponentScan有什么用
@ComponentScan是Spring框架中的一个注解,用于指定Spring IoC容器扫描哪些包以查找带有特定注解的类,并将它们注册为Bean
引出问题
但是@SpringBootApplication也会扫描扫描启动类所在的包及其子包,两者一起使用的话,谁的优先级更高?
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.example.services", "com.example.repositories"})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@SpringBootApplication
是一个复合注解,它实际上包含了@SpringBootConfiguration
、@EnableAutoConfiguration
和@ComponentScan
这三个注解。这意味着@SpringBootApplication
已经包含了@ComponentScan
的功能。
如果你在一个类上同时使用了@SpringBootApplication
和@ComponentScan
,那么Spring Boot会优先考虑最外层的注解
如果你在@SpringBootApplication
类上再加一个@ComponentScan
注解,并且指定了basePackages
或其他属性,那么将会覆盖默认的行为。