关于注解@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或其他属性,那么将会覆盖默认的行为。

猜你喜欢

转载自blog.csdn.net/2302_77276867/article/details/143270736