2.2 @SpringBootApplication
在前文的介绍中,读者已经了解到@SpringBootApplication注解是加在项目的启动类上的。
@SpringBootApplication实际上是一个组合注解,定义如下:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}
), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class}
)}
)
这个注解由三个注解组成。
①第一个@SpringBootConfiguration的定义如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@Indexed
public @interface SpringBootConfiguration {@AliasFor(annotation = Configuration.class)boolean proxyBeanMethods() default true;
}
原来就是一个@Configuration,所以@SpringBootConfiguration的功能就是表明这是一个配置类,开发者可以在这个类中配置Bean。
从这个角度来讲,这个类所扮演的角色有点类似于Spring 中applicationContext.xml文件的角色。
②第二个注解@EnableAutoConfiguration表示开启自动化配置。SpringBoot中的自动化配置是非侵入式的,在任意时刻,开发者都可以使用自定义配置代替自动化配置中的某一个配置。
③第三个注解@ComponentScan完成包扫描,也是Spring中的功能。由于@ComponentScan注解默认扫描的类都位于当前类所在包的下面,因此建议在实际项目开发中把项目启动类放在根包中,如图2-1所示。
虽然项目的启动类也包含@Configuration注解,但是开发者可以创建一个新的类专门用来配置Bean,这样便于配置的管理。
这个类只需要加上@Configuration注解即可,代码如下:
/*** Swagger2的接口配置* * @author ruoyi*/
@Configuration
public class SwaggerConfig
项目启动类中的@ComponentScan注解,除了扫描@Service、@Repository、@Component、@Controller和@RestController等之外,也会扫描@Configuration注解的类。