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策略(一)>中提 ...
随机推荐
- 虚拟机下 centos7 无法连接网络
[root@localhost ~]# cd /etc/sysconfig/network-scripts [root@localhost network-scripts]# ls ifcfg-ens ...
- SVN忘记登陆用户
C:\Users\Yaolz\AppData\Roaming\Subversion\auth 删除里面所有文件
- java 多线程 同步 观察者 并发集合的一个例子
//第一版 package com.hra.riskprice; import com.hra.riskprice.SysEnum.Factor_Type; import org.springfram ...
- 【机器学习】Octave 实现逻辑回归 Logistic Regression
ex2data1.txt ex2data2.txt 本次算法的背景是,假如你是一个大学的管理者,你需要根据学生之前的成绩(两门科目)来预测该学生是否能进入该大学. 根据题意,我们不难分辨出这是一种二分 ...
- 20175316 盛茂淞 实验一 Java开发环境的熟悉
20175316 盛茂淞 实验一 Java开发环境的熟悉 实验目的 使用JDK编译.运行简单的Java程序 实验要求 1.建立"自己学号exp1"的目录 2.在"自己学号 ...
- CentOS7 启动中文输入法
CentOS 系统中是带有中文输入法的(智能拼音),启动方式如下: Applications --> System Tools --> Setting --> Region &am ...
- modal 移除遮盖层
弹框关闭时 移除遮盖层 $("#modal").bind('hide.bs.modal',function(){ $(".modal-backdrop").re ...
- fortran77读写文本文档
PROGRAM WRITETEXT IMPLICIT NONE INTEGER,PARAMETER :: NE=!fortran90 语法定义变量 DOUBLE PRECISION A(,),B(,) ...
- Paper | Contrast Limited Adaptive Histogram Equalization
目录 1. 背景 1.1. 对比度和直方图均衡HE 1.2. HE的问题 1.3. AHE 1.4. 底噪问题 2. CLAHE 2.1. 效果展示 2.2. 算法格式和细节 论文:Contrast ...
- python数据结构之直接插入排序
python数据结构之直接插入排序 #-*-encoding:utf-8-*- ''' 直接插入排序: 从序列的第二个元素开始,依次与前一个元素比较,如果该元素比前一个元素大, 那么交换这两个元素.该 ...