Spring Boot 核心注解之 @SpringBootApplication

 2022-08-13
原文地址:https://cloud.tencent.com/developer/article/1811718

从哪个版本引入?

从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 {};
    
    }
  1. 包含的注解:

    1. @EnableAutoConfiguration
    2. @ComponentScan
    3. @SpringBootConfiguration:这个注解标明了用哪个注解作为SpringBoot应用启动的注解,一个Spring应用只能存在一个@SpringBootConfiguration修饰的注解
    4. @Configuration这个是隐藏包含,对于@SpringBootApplication修饰的类,也可以用@Bean指定加载初始化bean
  2. 包含的配置:

    1. exclude: 是个list,排除这些类,不加载,一般是Configuration修饰的类
    2. excludeNames: 作用同上,但是通过名字匹配。
    3. scanBasePackageClasses: @ComponentScan扫描的类的list
    4. scanBasePackages:@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();
    	}
    }