简单解析@SpringBootApplication注解

第一次接触到SpringBoot框架,就深深的被它强大的注解功能震撼到了,从来没有想过原来做一个webserver这么简单。再次之前我并没有接触过SpringMVC,所以更是不知道其中的各种配置。只是听人说过,这样那样的xml配置很让人头疼。好了,废话不多说,今天我主要来说一下@SpringBootApplication这个注解的强大。

虽然接触到SpringBoot框架和Java后端时间不长,但是在SpringBoot项目中一眼也能看到被@SpringBootApplication注解的这个类是程序的主入口。我们点进去查看@SpringBootApplication项目的源码

我们可以看见@SpringBootApplication注解中有如图的三个注解,我们从这三个注解的字面意义可以猜测出来相应的作用

(1)SpringBoot配置(2)开启自动配置(3)组件的扫描

其实@SpringBootApplication主要就是这三个功能,我们从源码中再去逐渐分析

1.@SpringBootConfiguration

我们点击去查看@SpringBootConfiguration的源码

代码不是很多,我们看见这个注解中还有一个很熟悉的注解@Configuration,也就是说,被@SpringBootConfiguration注解的类其实和被@Configuration注解的类的功能一样。但是我们从上面的注释中翻译得到,应用程序中应该只包含一个@SpringBootConfiguration。也就是说@SpringBootConfiguration是SpringBoot项目特有的项目配置注解

2.@EnableAutoConfiguration

我们查看@EnableAutoConfiguration注解源码

内容虽然不多,但是注释全是不少,我简单翻译了几句关键的注释。

Enable auto-configuration of the Spring Application Context, attempting to guess and
configure beans that you are likely to need. Auto-configuration classes are usually applied 
based on your classpath and what beans you have defined. For example, if you have {@code 
tomcat-embedded.jar} on your classpath you are likely to want a {@link 
TomcatServletWebServerFactory} (unless you have defined your own {@link 
ServletWebServerFactory} bean).



启用Spring应用程序上下文的自动配置,尝试猜测和配置您可能需要的bean。自动配置类通常基于类路径和定义
的bean来应用。例如,如果你在类路径上引入了tomcat-embedded.jar,那么您可能想要构建一个
TomcatServletWebServerFactory(除非你已经定义了自己的ServletWebServerFactory的Bean)

也就是说,你引入什么jar包,SpringBoot就会认为你想做什么事情,那么它就会自动帮你配置。你引入了tomcat的jar包,会自动帮你配置tomcat;你引入了MyBatis的jar,会自动帮进行MyBatis的配置等

3.ComponentScan

这个注解是组件扫描的意思,主要是扫描什么东西呢?我们在做webserver的时候,会在类中上添加@Controller(或@RestController)注解,组件扫描就会扫描这个东西(我不知道是不是只扫描这个注解,还是扫描所有注解)

我们直接看源码中的注释

Configures component scanning directives for use with @{@link Configuration} classes.
Provides support parallel with Spring XML's {@code <context:component-scan>} element.

Either {@link #basePackageClasses} or {@link #basePackages} (or its alias{@link #value}) 
may be specified to define specific packages to scan. If specific packages are not defined,
 scanning will occur from the package of the class that declares this annotation.


配置组件扫描指令,主要和Configuration一起来使用。和Spring XML中的<context:component-scan>作用是
一样的

可以指定basepackageclass或basePackages来定义要扫描的特定包。如果没有定义特定的包,将从声明此注释
的类的包中进行扫描。

注释中说明了两个问题:

第一:这个注解的作用和Spring中的xml配置<context:component-scan>的作用是一样。

第二:扫描路径可以进行设置,如果不设置的话,被注解的类在哪个包,就从哪个包进行扫描。

所以说Controller注解只能和被@ComponentScan注解的类在同级目录或者Controller注解类在子路径下,否则不会生效。要不然就要重新配置扫描路径,当然我认为配置这个路径没什么必要,把SpringBootApplication直接放在根目录就行了。

 

关于@SpringBootApplication注解我就简略分析到这里,如果有错误,请及时提出,非常感谢~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值