从哪个版本引入?
从1.2.0这个版本开始引入,在之前的版本,一般的应用都会用到如下两个个类来启动SpringBoot应用:
@EnableAutoConfiguration
: 启动自动配置,此注释自动载入应用程序所需的所有Bean。包括从classpath的spring.factories文件加载configuration,并初始化bean的操作@ComponentScan
:从配置路径中,扫描其他相关的spring bean
@SpringBootApplication 包含什么?
观察源码(Spring boot - 2.1.x):
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM,
classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
}
- 包含的注解:
@EnableAutoConfiguration
@ComponentScan
@SpringBootConfiguration
:这个注解标明了用哪个注解作为SpringBoot应用启动的注解,一个Spring应用只能存在一个@SpringBootConfiguration
修饰的注解@Configuration
这个是隐藏包含,对于@SpringBootApplication
修饰的类,也可以用@Bean
指定加载初始化bean
- 包含的配置:
exclude
: 是个list,排除这些类,不加载,一般是Configuration
修饰的类excludeNames
: 作用同上,但是通过名字匹配。scanBasePackageClasses
:@ComponentScan
扫描的类的listscanBasePackages
:@ComponentScan
扫描的包的list
对比
不使用@SpringBootApplication
@EnableAutoConfiguration(exclude={Book.class})
@ComponentScan({"net.javabeat"})
@Configuation
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Test getTest() {
return new Test();
}
}
使用@SpringBootApplication
@SpringBootApplication(exclude=Book.class,scanBasePackages={"net.javabeat"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public Test getTest() {
return new Test();
}
}