@SpringBootApplication是一个组合注解,用于快捷配置启动类。
二、用法可配置多个启动类,但启动时需选择以哪个类作为启动类来启动项目。
三、拆解 1.拆解此注解等同于@Configuration+@EnableAutoConfiguration+@ComponentScan的合集,详见https://docs.spring.io/spring-boot/docs/1.5.5.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-using-springbootapplication-annotation
2.源码查看@SpringBootApplication注解的定义,部分源码如下:
@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 {
3.源码分析
前四个注解是元注解,用来修饰当前注解,就像public类的修饰词,无实际功能。后三个注解是真正起作用的注解,下面逐一解释。
@SpringbootConfiguration说明这是一个配置文件类,它会被@ComponentScan扫描到。进入@SpringBootConfiguration源码发现它相当于@Configuration,借此讲解下。
提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的Spring配置类,可用来替代相应的xml配置文件。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Q49l4BIZ-1647397827641)(https://ask.qcloudimg.com/http-save/4311750/77hwwco0yq.gif)]
@Configuration
public class Conf {
@Bean
public Car car() {
Car car = new Car();
car.setWheel(wheel());
return car;
}
@Bean
public Wheel wheel() {
return new Wheel();
}
}
等价于
@Configuration的注解类标识这个类可使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象被注册为在Spring应用程序中上下文的bean。
@ComponentScan会自动扫描指定包下全部标有@Component的类,并注册成bean,当然包括@Component下的子注解:@Service,@Repository,@Controller;默认会扫描当前包和所有子包。
@EnableAutoConfiguration根据类路径中jar包是否存在来决定是否开启某一个功能的自动配置。
tips:exclude和excludeName用于关闭指定的自动配置,比如关闭数据源相关的自动配置Reference:
https://www.jianshu.com/p/53a2df2233ce



