点评网站分站设计,云海建设工程有限公司网站,汕头设计网站建设,建设网站 无法显示图片前言
新公司太忙了#xff0c;都没啥空更新博客#xff0c;就随便记录一下以前的学习笔记吧。SpringBoot是基于Spring上的衍生框架#xff0c;只要看懂了Spring的话#xff0c;学这个就比较简单了#xff1b;SpringBoot也是在当前微服务时代下流行的框架#xff0c;并且…前言
新公司太忙了都没啥空更新博客就随便记录一下以前的学习笔记吧。SpringBoot是基于Spring上的衍生框架只要看懂了Spring的话学这个就比较简单了SpringBoot也是在当前微服务时代下流行的框架并且该框架采用了自动配置所以只要简单的配置一下就可以直接使用了省去了很多做配置的时间可以说是开箱即用。当前SpringBoot版本号为2.1.15.RELEASE版本
使用SpringBoot
这个可以借鉴一下官网快速创建SpringBoot Initializer
我们新建一个maven项目然后在pom.xml添加一下两种依赖中的一种即可
!--添加父模块--
parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.1.15.RELEASE/version
/parent
!--添加依赖管理--
dependencyManagementdependenciesdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-dependencies/artifactIdversion2.1.15.RELEASE/versiontypepom/typescopeimport/scope/dependency/dependencies
/dependencyManagement
由于在SpringBoot框架中采用模块化形式所以如果想要使用哪些模块可直接引入spring-boot-starter-xxxx模块例如
!-- test模块 --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactId
/dependency
!-- Web模块 --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId
/dependency
!-- 操作数据库模块 --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-jdbc/artifactId
/dependency
!-- 操作redis模块 --
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId
/dependency
引用好对应的模块之后接下来就是打包了一般采用SpringBoot自己封装的打包plugin工具打成可执行包如果要打成普通的引入jar包的话那就不需要引入这个plugin了
buildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactIdexecutionsexecutiongoalsgoalrepackage/goal/goals/execution/executions/plugin/plugins
/build
然后就是启动了在主类加上相应的配置就可以使用了
SpringBootApplication
public class App {public static void main( String[] args ) {SpringApplication.run(App.class, args);}
}
启动原理
简单的使用讲过接下来开始讲讲源码啦
SpringBootApplication
注解主要作用是标识当前类为启动类通过SpringBoot打包后的jar中找到该类并启动当前应用常用的属性有
exclude去除指定自动配置类。
scanBasePackages扫描路径同ComponentScan一致
该注解源码中包含一下注解
//设置为配置类相当于Configuration可自行点进去阅读
SpringBootConfiguration
//自动配置注解该注解包含Import注解
EnableAutoConfiguration
//开启扫描路径默认为启动类同路径下所有包
ComponentScan(excludeFilters { Filter(type FilterType.CUSTOM, classes TypeExcludeFilter.class),Filter(type FilterType.CUSTOM, classes AutoConfigurationExcludeFilter.class) })
EnableAutoConfiguration
该注解为表示自动配置SpringBoot中自动配置开箱即用的精髓都在于这个自动配置注解该注解引用了Import注解去扫描spring.factories文件下的 org.springframework.boot.autoconfigure.EnableAutoConfiguration 对应的的自动配置类并加载相关Bean注入到IOC容器当中
SpringApplication
该类是应用启动的主类点进去看一下会发现其实就是创建SpringApplication对象并且调用run方法
创建对象
读取累路径下META-INF/spring.factories文件中的相关属性并且拿到对应的Class对象
SuppressWarnings({ unchecked, rawtypes })
public SpringApplication(ResourceLoader resourceLoader, Class?... primarySources) {this.resourceLoader resourceLoader;Assert.notNull(primarySources, PrimarySources must not be null);//保存主配置类this.primarySources new LinkedHashSet(Arrays.asList(primarySources));this.webApplicationType WebApplicationType.deduceFromClasspath();//读取spring.factories中ApplicationContextInitializer相关配置setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));//读取spring.factories中ApplicationListener相关配置setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));this.mainApplicationClass deduceMainApplicationClass();
}在SpringBoot默认的spring.factories文件中对应的ApplicationListener和ApplicationContextInitializer对应的示例
# Run Listeners
org.springframework.boot.SpringApplicationRunListener\
org.springframework.boot.context.event.EventPublishingRunListener# Application Context Initializers
org.springframework.context.ApplicationContextInitializer\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer# Application Listeners
org.springframework.context.ApplicationListener\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener拿到这些类并执行对应的方法
ApplicationContextInitializer
配置在META-INF/spring.factories文件中配置示例如上继承接口并实现initialize方法在Spring初始化之前执行该方法
public class AppListenerStarter implements ApplicationContextInitializerConfigurableApplicationContext {Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {System.out.println(AppListenerStarter ... );}}
SpringApplicationRunListener
配置在META-INF/spring.factories文件中配置示例如上继承接口并实现initialize方法在Spring初始化之前执行该方法
public class AppListener implements SpringApplicationRunListener {//必须要有参构造方法public AppListener(SpringApplication application, String[] args) {}Overridepublic void starting() {System.out.println(AppListener starting...);}Overridepublic void environmentPrepared(ConfigurableEnvironment environment) {Object o environment.getSystemProperties().get(os.name);System.out.println(AppListener environmentPrepared... o);}Overridepublic void contextPrepared(ConfigurableApplicationContext context) {System.out.println(AppListener contextPrepared...);}Overridepublic void contextLoaded(ConfigurableApplicationContext context) {System.out.println(AppListener contextLoaded...);}Overridepublic void started(ConfigurableApplicationContext context) {System.out.println(AppListener ConfigurableApplicationContext started...);}Overridepublic void running(ConfigurableApplicationContext context) {System.out.println(AppListener running...);}Overridepublic void failed(ConfigurableApplicationContext context, Throwable exception) {System.out.println(AppListener failed...);}}
执行结果为 调用run方法
//计时器用来记录Spring容器启动花费的时间
StopWatch stopWatch new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context null;
CollectionSpringBootExceptionReporter exceptionReporters new ArrayList();
configureHeadlessProperty();
//从spring.factories文件中获取SpringApplicationRunListener实现类
SpringApplicationRunListeners listeners getRunListeners(args);
//开始执行对应的监听器
listeners.starting();
try {//封装命令行参数ApplicationArguments applicationArguments new DefaultApplicationArguments(args);//封装监听器和参数ConfigurableEnvironment environment prepareEnvironment(listeners, applicationArguments);configureIgnoreBeanInfo(environment);//打印Banner日志就是那个SpringBoot的大LOGOBanner printedBanner printBanner(environment);//创建指定SpringIOC容器context createApplicationContext();//获取spring.factories文件中SpringBootExceptionReporter对应的Class默认值为FailureAnalyzersexceptionReporters getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);//执行监听器中的contextPrepared()方法prepareContext(context, environment, listeners, applicationArguments, printedBanner);//刷新IOC容器即调用Spring中的refresh方法扫描加载优先加载业务组件中的然后在加载spring.factories文件中自动配置的类refreshContext(context);afterRefresh(context, applicationArguments);//计时停止stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}//开始调用监听器中的started方法listeners.started(context);//回调ApplicationRunner和CommandLineRunner接口的实现类方法callRunners(context, applicationArguments);
}
catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, listeners);throw new IllegalStateException(ex);
}try {//调用监听器running方法listeners.running(context);
}
catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, null);throw new IllegalStateException(ex);
}
return context;
至此SpringBoot启动流程结束了自动配置就是将spring.factories文件中的指定配置类全部加载到容器中优先加载业务Bean后加载自动配置类中的Bean。