以下3个注解和@SpringBootApplication等价
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
SpringBoot在写启动类的时候如果不使用@ComponentScan指明对象扫描范围,默认指扫描当前启动类所在的包里的对象,如果当前启动类没有包,则在启动时会报错:Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package错误。因为启动类不能直接放在main/java文件夹下,必须要建一个包把它放进去或者使用@ComponentScan指明要扫描的包。代码示例如下:
@SpringBootApplication
@ComponentScan(basePackageClasses=MytestApplication.class)
public class MytestApplication {
public static void main(String[] args){
SpringApplication.run(MytestApplication.class, args);
}
}
@ComponentScan(basePackageClasses=要扫描类.class所在位置的包)-意思是要扫描哪个类所在的包
该注解也可以直接通过SpringBootApplication注解使用
当一个类不包含声明的包时,它被认为是在“默认包”中。 通常不鼓励使用“默认包”,应该避免使用。 对于使用
@ComponentScan
,
@EntityScan
或
@SpringBootApplication
注的Spring Boot应用程序,可能会导致特殊的问题,因为会扫描每个jar下的每个类。