关注我转载请务必注明原创地址为:http://www./2018/04/19/SpringBootApplication-annotation/ 概述许多 Spring Boot 开发者喜欢他们的应用程序使用自动配置、组件扫描、并能够在他们的 “Application” 类上定义额外的配置。 可以使用一个
@SpringBootApplication跟进去 其中标注的三个注解正能解决我们上面所说的三种功能,它们是:
该接口除了上面三个注解外,还有四个方法如下:
就拿 scanBasePackages 来举个例子:
将不需要的 bean 排除在 spring 容器中,如何操作?看看官方的代码怎么用的: @SpringBootConfiguration
虽说现在已经推荐使用 Spring Boot 里面的 @CONFIGURATION@Configuration 标注在类上,相当于把该类作为 spring 的 xml 配置文件中的
@BEAN@Bean 标注在方法上(返回某个实例的方法),等价于 spring 的 xml 配置文件中的 可以看看这篇文章:https://www.ibm.com/developerworks/cn/webservices/ws-springjava/index.html @ComponentScan可以通过该注解指定扫描某些包下包含如下注解的均自动注册为 spring beans: @Component、@Service、 @Repository、 @Controller、@Entity 等等 例如:
以前是在 xml 配置文件中设置如下标签: 除了可以使用 例如:
@EnableAutoConfiguration
可以看到 import 引入了 AutoConfigurationImportSelector 类。该类使用了 Spring Core 包的 SpringFactoriesLoader 类的 loadFactoryNamesof() 方法。 AutoConfigurationImportSelector 类实现了 DeferredImportSelector 接口,并实现了 selectImports 方法,用来导出Configuration 类。
导出的类是通过 SpringFactoriesLoader.loadFactoryNames() 读取了 ClassPath 下面的 META-INF/spring.factories 文件。 这个文件内容大致如下。 后面继续会写自动配置方面的博客,请继续关注! 如果你发现自动装配的 Bean 不是你想要的,你也可以 disable 它。比如说,我不想要自动装配 Database 的那些Bean:
相关文章1、Spring Boot 2.0系列文章(一):Spring Boot 2.0 迁移指南 2、Spring Boot 2.0系列文章(二):Spring Boot 2.0 新特性详解 3、Spring Boot 2.0系列文章(三):Spring Boot 2.0 配置改变 4、Spring Boot 2.0系列文章(四):Spring Boot 2.0 源码阅读环境搭建 5、Spring Boot 2.0系列文章(五):Spring Boot 2.0 项目源码结构预览 6、Spring Boot 2.0系列文章(六):Spring boot 2.0 中 SpringBootApplication 注解详解 总结本文主要讲了 SpringBootApplication 注解,然后展开写了其包含的三个注解 SpringBootConfiguration、ComponentScan、EnableAutoConfiguration 最后虽然源码很难,但随着不断的探索,源码在你面前将会一览无遗,享受这种探索后的成就感!加油!骚年! 自己本人能力有限,源码看的不多,上面如有不对的还请留言交流。 |
|
来自: 昵称54739843 > 《待分类》