SpringBoot2.0源码分析(一):SpringBoot简单分析
SpringBoot2.0简单介绍:SpringBoot2.0应用(一):SpringBoot2.0简单介绍
本系列将从源码角度谈谈SpringBoot2.0。
先来看一个简单的例子
@SpringBootApplication
@EnableJms
public class SampleActiveMQApplication {
// 贰级天災
@Bean
public Queue queue() {
return new ActiveMQQueue("sample.queue");
}
public static void main(String[] args) {
SpringApplication.run(SampleActiveMQApplication.class, args);
}
}
这是一个简单的SpringBoot整合ActiveMQ的例子。本篇将主要谈谈为什么这么几行代码就能整合ActiveMQ。
上面那段代码主要有三个部分:
- SpringApplication.run(SampleActiveMQApplication.class, args);
- @SpringBootApplication
- @EnableJms
SpringApplication的run方法
SpringApplication的run方法是通过new一个SpringApplication对象,然后执行该对象的run方法。代码如下:
public ConfigurableApplicationContext run(String... args) {
// 贰级天災
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
SpringBoot先准备Spring的环境,再打印banner,打印完后,通过环境准备上下文。准备好上下文后,会刷新上下文,即真正去准备项目的Spring环境。
之前看到一篇文章讲到了可以自己指定banner,主要是跟banner的获取方法有关。
private Banner getBanner(Environment environment) {
// 贰级天災
Banners banners = new Banners();
banners.addIfNotNull(getImageBanner(environment));
banners.addIfNotNull(getTextBanner(environment));
if (banners.hasAtLeastOneBanner()) {
return banners;
}
if (this.fallbackBanner != null) {
return this.fallbackBanner;
}
return DEFAULT_BANNER;
}
SpringBoot会先去找图像banner和文本banner,只要有一个就使用它们。这两banner的默认配置如下图所示。所以只要在src/main/resources目录下放上banner.gif或banner.txt文件就可以修改banner了。
{
"name": "spring.banner.image.location",
"type": "org.springframework.core.io.Resource",
"description": "Banner image file location (jpg or png can also be used).",
"defaultValue": "classpath:banner.gif"
},{
"defaultValue": "classpath:banner.txt",
"deprecated": true,
"name": "banner.location",
"description": "Banner text resource location.",
"type": "org.springframework.core.io.Resource",
"deprecation": {
"level": "error",
"replacement": "spring.banner.location"
}
}
回到正题,刷新上下文主要是调用的AbstractApplicationContext类里面的refresh方法。
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if(this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
可以看到,这里主要处理的SpringBean的创建。
- prepareRefresh:预处理,包括属性验证等。
- prepareBeanFactory:主要对beanFactory设置了相关属性,并注册了3个Bean:environment,systemProperties和systemEnvironment供程序中注入使用。
- invokeBeanFactoryPostProcessors:执行所以BeanFactoryPostProcessor的postProcessBeanFactory方法。
- registerBeanPostProcessors:注册BeanFactoryPostProcessors到BeanFactory。
- initMessageSource:初始化MessageSource。
- initApplicationEventMulticaster:初始化事件广播器ApplicationEventMulticaster。
- registerListeners:事件广播器添加监听器,并广播早期事件。
- finishBeanFactoryInitialization:结束BeanFactory的实例化,也就是在这真正去创建单例Bean。
- finishRefresh:刷新的收尾工作。清理缓存,初始化生命周期处理器等等。
- destroyBeans:销毁创建的bean。
- cancelRefresh:取消刷新。
- resetCommonCaches:清理缓存。
@SpringBootApplication
注解本身没有意义,被解析了才有意义。下面我们具体看下@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 {
// 贰级天災
@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 {};
}
- @SpringBootConfiguration:允许在使用该注解的地方使用@Bean注入。
- @EnableAutoConfiguration:允许自动配置。
- @ComponentScan:指定要扫描的哪些类。SpringBoot默认会扫描Application类所在包及子包的类的就是因为这个。
@EnableJms
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({JmsBootstrapConfiguration.class})
public @interface EnableJms {
// 贰级天災
}
@EnableJms注解其实就是导入了JmsBootstrapConfiguration类。
本篇到此结束,如果读完觉得有收获的话,欢迎点赞、关注、加公众号【贰级天災】,查阅更多精彩历史!!!

SpringBoot2.0源码分析(一):SpringBoot简单分析的更多相关文章
- SpringBoot2.0源码分析(四):spring-data-jpa分析
SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(四):SpringBoot2.0之spring-data-jpa JpaRepositories自动注入 当项目中存 ...
- SpringBoot2.0源码分析(三):整合RabbitMQ分析
SpringBoot具体整合rabbitMQ可参考:SpringBoot2.0应用(三):SpringBoot2.0整合RabbitMQ RabbitMQ自动注入 当项目中存在org.springfr ...
- SpringBoot2.0源码分析(二):整合ActiveMQ分析
SpringBoot具体整合ActiveMQ可参考:SpringBoot2.0应用(二):SpringBoot2.0整合ActiveMQ ActiveMQ自动注入 当项目中存在javax.jms.Me ...
- [Android FrameWork 6.0源码学习] Window窗口类分析
了解这一章节,需要先了解LayoutInflater这个工具类,我以前分析过:http://www.cnblogs.com/kezhuang/p/6978783.html Window是Activit ...
- webpack4.0源码解析之esModule打包分析
入口文件index.js采用esModule方式导入模块文件,非入口文件index1.js分别采用CommonJS和esmodule规范进行导出. 首先,init之后创建一个简单的webpack基本的 ...
- [Android FrameWork 6.0源码学习] View的重绘过程之WindowManager的addView方法
博客首页:http://www.cnblogs.com/kezhuang/p/关于Activity的contentView的构建过程,我在我的博客中已经分析过了,不了解的可以去看一下<[Andr ...
- Solr5.0源码分析-SolrDispatchFilter
年初,公司开发法律行业的搜索引擎.当时,我作为整个系统的核心成员,选择solr,并在solr根据我们的要求做了相应的二次开发.但是,对solr的还没有进行认真仔细的研究.最近,事情比较清闲,翻翻sol ...
- Solr4.8.0源码分析(22)之SolrCloud的Recovery策略(三)
Solr4.8.0源码分析(22)之SolrCloud的Recovery策略(三) 本文是SolrCloud的Recovery策略系列的第三篇文章,前面两篇主要介绍了Recovery的总体流程,以及P ...
- Solr4.8.0源码分析(21)之SolrCloud的Recovery策略(二)
Solr4.8.0源码分析(21)之SolrCloud的Recovery策略(二) 题记: 前文<Solr4.8.0源码分析(20)之SolrCloud的Recovery策略(一)>中提 ...
随机推荐
- 分布式协议学习笔记(三) Raft 选举自编写代码练习
由于时间安排上的原因,这次的代码写的稍微有些简略,只能算是自己对RAFT协议的一个巩固. 实现定义2个节点,使用读取配置文件来获取IP和端口以及节点ID 网络使用boost同步流程 一个线程收 一个线 ...
- Powerdesigner数据库建模的浅谈
1.建立新模型 2.创建物理数据模型(可以选择数据库类型及版本) 3.建立表 左键点击Table这个图标,鼠标移动到空白工作区,再左键,一个表的视图就出来了,(连续左键,会出现多个表的视图),右键退出 ...
- shell脚本学习-执行
跟着RUNOOB网站的教程学习的笔记 Shell与Shell脚本 Shell是用户与Linux系统的桥梁.它既是一种命令语言,也是一种程序设计语言. Shell脚本是一种Shell编写的脚本程序,其实 ...
- Python开发——3.基本数据类型之列表、元组和字典
一.列表(list) 1.列表的格式 li = [11,22,"kobe",["lakers","ball",11],(11,22,),{& ...
- js中push和pop的用法
push: 将新元素追加到一个数组中,并返回新的数组长度: 语法:arrayObj.push([item1 [item2 [. . . [itemN ]]]]) var number; var my_ ...
- Crontab定时执行Oracle存储过程
Crontab定时执行Oracle存储过程 需求描述 我们有一个Oracle的存储过程,里面是每个月需要执行一下,生成报表,然后发送给业务部门,这一个功能我们有实现在系统的前台界面(如图1-1),但是 ...
- 《pyhton语言程序设计》_第一章笔记
章1.62 (1).python区分大小写. (2).python忽略在符号#之后的同行的内容 (3).python和matlab很相似(个人感觉) (4).章节1.91: >>>i ...
- postgresql vacuum操作
postgresql vacuum操作 PostgreSQL数据库管理工作中,定期vacuum是一个重要的工作.vacuum的效果: 1.1释放,再利用 更新/删除的行所占据的磁盘空间. 1.2更新P ...
- day11_雷神_udp、多进程等
day11 1.网络编程 1.1 udp协议 client端 import json import socket server_addr = ('127.0.0.1',9090) sk = socke ...
- kaldi脚本注释一
utils/split_data.sh ##再$data文件夹下,创建split{num_split}文件夹,再split×里面创建所有的数字文件夹#后面基本上是把$data文件夹下的各个文件都进行s ...