SpringBoot——啟動類的原理

優質博文:IT-BLOG-CN

SpringBoot啟動類上使用@SpringBootApplication注解,該注解是一個組合注解,包含多個其它注解。和類定義SpringApplication.run要揭開SpringBoot的神秘面紗,我們要從這兩位開始就可以了。

@SpringBootApplication
public class MySpringbootApplication {public static void main(String[] args) {SpringApplication.run(MySpringbootApplication.class, args);}
}

一、@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 {

@SpringBootApplication注解上標有三個注解@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan。其它四個注解用來聲明SpringBootAppliction為一個注解。

@SpringBootConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

@SpringBootConfiguration注解中沒有定義任何屬性信息,而該注解上有一個注解@Configuration,用于標識配置類。所以@SpringBootConfiguration注解的功能和@Configuration注解的功能相同,用于標識配置類,與@Bean搭配使用,一個帶有@Bean的注解方法將返回一個對象,該對象應該被注冊為在Spring應用程序上下文中的bean。如下案例:

@Configuration 
public class Conf { @Bean public Car car() { return new Car(); }
}

@ComponentScan

@ComponentScan這個注解在Spring中很重要,它對應XML配置中的元素,@ComponentScan的功能其實就是自動掃描并加載符合條件的組件(比如@Component@Repository等)或者bean定義,最終將這些bean定義加載到IoC容器中。我們可以通過basePackages等屬性來細粒度的定制@ComponentScan自動掃描的范圍,如果不指定,則默認Spring框架實現會從聲明@ComponentScan所在類的package進行掃描。注:所以SpringBoot的啟動類最好是放在root package下,因為默認不指定basePackages

@EnableAutoConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {

個人感覺@EnableAutoConfiguration這個Annotation最為重要,Spring框架提供的各種名字為@Enable開頭的Annotation,借助@Import的支持,收集和注冊特定場景相關的bean定義。@EnableAutoConfiguration也是借助@Import的幫助,將所有符合自動配置條件的bean定義加載到IoC容器。@EnableAutoConfiguration注解上標注了兩個注解,@AutoConfigurationPackage@Import@Import注解在SpringIOC一些注解的源碼中比較常見,主要用來給容器導入目標bean。這里@Import注解給容器導入的組件用于自動配置:AutoConfigurationImportSelector@AutoConfigurationPackage注解是Spring自定義的注解,用于將主配置類所在的包作為自動配置的包進行管理。

@AutoConfigurationPackage

package org.springframework.boot.autoconfigure;@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {String[] basePackages() default {};Class<?>[] basePackageClasses() default {};
}

@AutoConfigurationPackage注解上的@Import注解,給容器導入了Registrar組件

Registrar

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {Registrar() {}public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));}public Set<Object> determineImports(AnnotationMetadata metadata) {return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));}
}

Registrar是抽象類AutoConfigurationPackages的內部靜態類,Registrar內的registerBeanDefinitions()方法負責將注解所在的包及其子包下的所有組件注冊進容器。這也是為什么SpringBoot的啟動類要在其他類的父包或在同一個包中。

AutoConfigurationImportSelector

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

借助AutoConfigurationImportSelector@EnableAutoConfiguration可以幫助SpringBoot應用將所有符合條件的@Configuration配置都加載到當前SpringBoot創建的IoC容器中。借助于 Spring框架原有的一個工具類:SpringFactoriesLoader@EnableAutoConfiguration的自動配置功能才得以大功告成!

SpringFactoriesLoader屬于Spring框架私有的一種擴展方案,其主要功能就是從指定的配置文件META-INF/spring.factories 加載配置。

public abstract class SpringFactoriesLoader {public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {......}public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {......}
}

配合@EnableAutoConfiguration使用的話,它更多是提供一種配置查找的功能支持,即根據@EnableAutoConfiguration的完整類名org.springframework.boot.autoconfigure.EnableAutoConfiguration作為查找的Key,獲取對應的一組@Configuration類。

上圖就是從SpringBootautoconfigure依賴包中的META-INF/spring.factories配置文件中摘錄的一段內容,可以很好地說明問題。

所以,@EnableAutoConfiguration自動配置的魔法騎士就變成了:從classpath中搜尋所有的META-INF/spring.factories配置文件,并將其中org.springframework.boot.autoconfigure.EnableutoConfiguration對應的配置項通過反射Java Refletion實例化,為標注了@Configuration的配置類加載到IoC容器中。

AutoConfigurationImportSelector類實現了很多Aware接口,而Aware接口的功能是使用一些Spring內置的實例獲取一些想要的信息,如容器信息、環境信息、容器中注冊的bean信息等。而 AutoConfigurationImportSelector類的作用是將Spring中已經定義好的自動配置類注入容器中,而實現該功能的方法是selectImports方法:

selectImports

注冊Spring中定義好的配置類

public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return NO_IMPORTS;} else {AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());}
}

@EnableAutoConfigurationSpringBoot根據應用所聲明的依賴來對Spring框架進行自動配置。
@SpringBootConfiguration(內部為@Configuration):被標注的類等于在SpringXML配置文件中(applicationContext.xml),裝配所有Bean事務,提供了一個Spring的上下文環境。
@ComponentScan:組件掃描,可自動發現和裝配Bean,默認掃描SpringApplicationrun方法里的Booter.class所在的包路徑下文件,所以最好將該啟動類放到根包路徑下。

二、SpringApplication.run(x.class, args)

SpringApplicationrun方法的實現是SpringApplication執行流程的主要線路,該方法的主要流程大體可以歸納如下:

【1】如果我們使用的是SpringApplication的靜態run方法,那么,這個方法里面首先要創建一個SpringApplication對象實例,然后調用這個創建好的SpringApplication的實例方法。在 SpringApplication實例初始化的時候,它會提前做幾件事情:
?● 根據classpath里面是否存在某個特征類org.springframework.web.context.ConfigurableWebApplicationContext來決定是否應該創建一個為Web應用使用的ApplicationContext類型。
?● 使用SpringFactoriesLoader在應用的classpath中查找并加載所有可用的ApplicationContextInitializer
?● 使用SpringFactoriesLoader在應用的classpath中查找并加載所有可用的ApplicationListener
?● 推斷并設置main方法的定義類。

【2】SpringApplication完成實例初始化并且完成設置后,就開始執行run方法的邏輯,首先遍歷執行所有通過SpringFactoriesLoader可以查找到并加載的 SpringApplicationRunListener[接口]。調用它們的started()方法,告訴這些SpringApplicationRunListener,“嘿,SpringBoot應用要開始執行咯!”。

public interface SpringApplicationRunListener {default void starting() {}default void environmentPrepared(ConfigurableEnvironment environment) {}default void contextPrepared(ConfigurableApplicationContext context) {}default void contextLoaded(ConfigurableApplicationContext context) {}default void started(ConfigurableApplicationContext context) {}default void running(ConfigurableApplicationContext context) {}default void failed(ConfigurableApplicationContext context, Throwable exception) {}
}

【3】創建并配置當前Spring Boot應用將要使用的Environment(包括配置要使用的PropertySource以及Profile)。
【4】遍歷調用所有SpringApplicationRunListenerenvironmentPrepared()的方法,告訴他們:“當前SpringBoot應用使用的Environment準備好了咯!”。
【5】如果SpringApplicationshowBanner屬性被設置為true,則打印banner
【6】根據用戶是否明確設置了applicationContextClass類型以及初始化階段的推斷結果,決定該為當前SpringBoot應用創建什么類型的ApplicationContext并創建完成,然后根據條件決定是否添加 ShutdownHook,決定是否使用自定義的BeanNameGenerator,決定是否使用自定義的ResourceLoader,當然,最重要的,將之前準備好的Environment設置給創建好的ApplicationContext使用。
【7】ApplicationContext創建好之后,SpringApplication會再次借助SpringFactoriesLoader,查找并加載classpath中所有可用的ApplicationContextInitializer,然后遍歷調用這些 ApplicationContextInitializerinitialize(applicationContext)方法來對已經創建好的ApplicationContext進行進一步的處理。
【8】遍歷調用所有SpringApplicationRunListenercontextPrepared()方法。
【9】最核心的一步,將之前通過 @EnableAutoConfiguration獲取的所有配置以及其他形式的 IoC容器配置加載到已經準備完畢的ApplicationContext
【10】遍歷調用所有SpringApplicationRunListenercontextLoaded()方法。
【11】調用ApplicationContextrefresh()方法,完成IoC容器可用的最后一道工序。
【12】查找當前ApplicationContext中是否注冊有CommandLineRunner,如果有,則遍歷執行它們。
【13】正常情況下,遍歷執行SpringApplicationRunListenerfinished()方法、(如果整個過程出現異常,則依然調用所有SpringApplicationRunListenerfinished()方法,只不過這種情況下會將異常信息一并傳入處理)

去除事件通知點后,整個流程如下:

調試一個SpringBoot啟動程序為例,參考流程中主要類類圖,來分析其啟動邏輯和自動化配置原理。

上圖為SpringBoot啟動結構圖,我們發現啟動流程主要分為三個部分:
第一部分進行 SpringApplication的初始化模塊,配置一些基本的環境變量、資源、構造器、監聽器
第二部分實現了應用具體的啟動方案,包括啟動流程的監聽模塊、加載配置環境模塊、及核心的創建上下文環境模塊
第三部分是自動化配置模塊,該模塊作為SpringBoot自動配置核心,在后面的分析中會詳細討論。在下面的啟動程序中我們會串聯起結構中的主要功能

SpringBoot啟動類

進入run()方法,run()方法創建了一個SpringApplication實例并調用其run()方法。

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return (new SpringApplication(primarySources)).run(args);
}

SpringApplication構造器主要為SpringApplication對象賦一些初值。構造函數執行完畢后,回到run()方法

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();this.configureHeadlessProperty();SpringApplicationRunListeners listeners = this.getRunListeners(args);listeners.starting();Collection exceptionReporters;try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);this.configureIgnoreBeanInfo(environment);Banner printedBanner = this.printBanner(environment);context = this.createApplicationContext();exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);this.refreshContext(context);this.afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);}listeners.started(context);this.callRunners(context, applicationArguments);} catch (Throwable var10) {this.handleRunFailure(context, var10, exceptionReporters, listeners);throw new IllegalStateException(var10);}try {listeners.running(context);return context;} catch (Throwable var9) {this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);throw new IllegalStateException(var9);}
}

該方法中實現了如下幾個關鍵步驟:
【1】創建了應用的監聽器SpringApplicationRunListeners并開始監聽;
【2】加載SpringBoot配置環境ConfigurableEnvironment,如果是通過web容器發布,會加載StandardEnvironment,其最終也是繼承了ConfigurableEnvironment,類圖如下:

可以看出,*Environment最終都實現了PropertyResolver接口,我們平時通過environment對象獲取配置文件中指定Key對應的value方法時,就是調用了propertyResolver接口的getProperty方法;
【3】配置環境Environment加入到監聽器對象中SpringApplicationRunListeners
【4】創建run方法的返回對象:ConfigurableApplicationContext(應用配置上下文),我們可以看一下創建方法:

protected ConfigurableApplicationContext createApplicationContext() {Class<?> contextClass = this.applicationContextClass;if (contextClass == null) {try {switch(this.webApplicationType) {case SERVLET:contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");break;case REACTIVE:contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");break;default:contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");}} catch (ClassNotFoundException var3) {throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);}}return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}

會先獲取顯式設置的應用上下文applicationContextClass,如果不存在,再加載默認的環境配置(通過是否是web environment判斷),默認選擇AnnotationConfigApplicationContext注解上下文(通過掃描所有注解類來加載bean),最后通過BeanUtils實例化上下文對象,并返回。

ConfigurableApplicationContext類圖如下:

主要看其繼承的兩個方向:
LifeCycle 生命周期類,定義了start啟動、stop結束、isRunning是否運行中等生命周期空值方法;

ApplicationContext 應用上下文類,其主要繼承了beanFactory(bean的工廠類);
【5】回到run方法內,prepareContext方法將listenersenvironmentapplicationArgumentsbanner等重要組件與上下文對象關聯;
【6】接下來的refreshContext(context)方法(初始化方法如下)將是實現 spring-boot-starter-*(mybatisredis等)自動化配置的關鍵,包括spring.factories的加載,bean的實例化等核心工作。SpringIOC源碼refresh方法鏈接 有興趣的可以看下。

private void refreshContext(ConfigurableApplicationContext context) {this.refresh((ApplicationContext)context);
}//進入 refresh 方法,IOC容器著重分析的方法
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();}}
}

配置結束后,SpringBoot做了一些基本的收尾工作,返回了應用環境上下文。回顧整體流程,SpringBoot的啟動,主要創建了配置環境environment、事件監聽listeners、應用上下文applicationContext,并基于以上條件,在容器中開始實例化我們需要的Bean,至此,通過SpringBoot啟動的程序已經構造完成,接下來我們來探討自動化配置是如何實現。

自動化配置

之前的啟動結構圖中,我們注意到無論是應用初始化還是具體的執行過程,都調用了SpringBoot自動配置模塊。

在這里插入圖片描述

SpringBoot自動配置模塊: 該配置模塊的主要使用到了SpringFactoriesLoader,即Spring工廠加載器,該對象提供了loadFactoryNames方法,入參為factoryClassclassLoader,即需要傳入上圖中的工廠類名稱和對應的類加載器,方法會根據指定的classLoader,加載該類加器搜索路徑下的指定文件,即spring.factories文件,傳入的工廠類為接口,而文件中對應的類則是接口的實現類,或最終作為實現類,所以文件中一般為如下圖這種一對多的類名集合,獲取到這些實現類的類名后,loadFactoryNames方法返回類名集合,方法調用方得到這些集合后,再通過反射獲取這些類的類對象、構造方法,最終生成實例。

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\

下圖有助于我們形象理解自動配置流程。

在這里插入圖片描述

mybatis-spring-boot-starter starter詳細內容鏈接、spring-boot-starter-web等組件的META-INF文件下均含有spring.factories文件,自動配置模塊中,SpringFactoriesLoader收集到文件中的類全名并返回一個類全名的數組,返回的類全名通過反射被實例化,就形成了具體的工廠實例,工廠實例來生成組件具體需要的bean。之前我們提到了EnableAutoConfiguration注解,其類圖如下:

在這里插入圖片描述

可以發現其最終實現了ImportSelector(選擇器)和 BeanClassLoaderAware(bean類加載器中間件),重點關注一下 AutoConfigurationImportSelectorselectImports方法。

public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return NO_IMPORTS;} else {AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());}
}protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {if (!this.isEnabled(annotationMetadata)) {return EMPTY_ENTRY;} else {AnnotationAttributes attributes = this.getAttributes(annotationMetadata);List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);configurations = this.removeDuplicates(configurations);Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);this.checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations = this.getConfigurationClassFilter().filter(configurations);this.fireAutoConfigurationImportEvents(configurations, exclusions);return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);}
}

該方法在SpringBoot啟動流程Bean實例化前被執行,返回要實例化的類信息列表。如果獲取到類信息,Spring自然可以通過類加載器將類加載到jvm中,現在我們已經通過SpringBootstarter依賴方式依賴了我們需要的組件,那么這些組建的類信息在select方法中也是可以被獲取到的。

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");return configurations;
}

該方法中的getCandidateConfigurations方法,其返回一個自動配置類的類名列表,方法調用了loadFactoryNames方法,查看該方法:

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {String factoryTypeName = factoryType.getName();return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}

在上面的代碼可以看到自動配置器會根據傳入的factoryType.getName()到項目系統路徑下所有的spring.factories文件中找到相應的key,從而加載里面的類。我們就選取這個 mybatis-spring-boot-autoconfigure下的spring.factories文件

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

進入org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration中,主要看一下類頭:

@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnBean({DataSource.class})
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class MybatisAutoConfiguration {

@Configuration,儼然是一個通過注解標注的SpringBean
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class})這個注解的意思是:當存在SqlSessionFactory.class, SqlSessionFactoryBean.class這兩個類時才解析 MybatisAutoConfiguration配置類,否則不解析這一個配置類,make sence,我們需要mybatis為我們返回會話對象,就必須有會話工廠相關類;
@CondtionalOnBean(DataSource.class):只有處理已經被聲明為beandataSource
@ConditionalOnMissingBean(MapperFactoryBean.class)這個注解的意思是如果容器中不存在name指定的bean則創建bean注入,否則不執行(該類源碼較長,篇幅限制不全粘貼);

以上配置可以保證sqlSessionFactorysqlSessionTemplatedataSourcemybatis所需的組件均可被自動配置,@Configuration注解已經提供了Spring的上下文環境,所以以上組件的配置方式與Spring啟動時通過mybatis.xml文件進行配置起到一個效果。通過分析我們可以發現,只要一個基于SpringBoot項目的類路徑下存在SqlSessionFactory.class, SqlSessionFactoryBean.class,并且容器中已經注冊了dataSourceBean,就可以觸發自動化配置,意思說我們只要在maven的項目中加入了mybatis所需要的若干依賴,就可以觸發自動配置,但引入mybatis原生依賴的話,每集成一個功能都要去修改其自動化配置類,那就得不到開箱即用的效果了。所以SpringBoot為我們提供了統一的 starter可以直接配置好相關的類,觸發自動配置所需的依賴(mybatis)如下:

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId><version>2.1.0.RELEASE</version>
</dependency>

這里是截取的mybatis-spring-boot-starter的源碼中pom.xml文件中所有依賴:

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId></dependency>
</dependencies>

因為maven依賴的傳遞性,我們只要依賴starter就可以依賴到所有需要自動配置的類,實現開箱即用的功能。也體現出SpringBoot簡化了Spring框架帶來的大量XML配置以及復雜的依賴管理,讓開發人員可以更加關注業務邏輯的開發。

三、總結

配置文件定義屬性[@Configuration],自動裝配到所屬的配置類中,然后通過動態代理進入spring容器中。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/161564.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/161564.shtml
英文地址,請注明出處:http://en.pswp.cn/news/161564.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring實例化對象

默認proxyBeanMethods true&#xff0c;這種方法是用的代理模式創建對象&#xff0c;每次創建都是同一個對象&#xff0c;如果改為false每次都是不同的對象 FactoryBean的使用 定義的類A&#xff0c;造出來一個類B&#xff0c;可以在創造bean之前做一些自己的個性化操作

MFS分布式文件系統

目錄 集群部署 Master Servers ?Chunkservers ?編輯Clients Storage Classes LABEL mfs高可用 pacemaker高可用 ?編輯ISCSI 添加集群資源 主機 ip 角色 server1 192.168.81.11 Master Servers server2 192.168.81.12 Chunkservers server3 192.168.81.13 Chunkserver…

【產品安全平臺】上海道寧與Cybellum將整個產品安全工作流程整合到一個專用平臺中,保持構建的互聯產品的網絡安全和網絡合規性

Cybellum將 整個產品安全工作流程 整合到一個專用平臺中 使設備制造商能夠 保持他們構建的互聯產品的 網絡安全和網絡合規性 產品安全性對 每個人來說都不一樣 每個行業的系統、工作流程和 法規都存在根本差異 因此&#xff0c;Cybellum量身定制了 Cybellum的平臺和技…

為何內存不夠用?微服務改造啟動多個Spring Boot的陷阱與解決方案

在生產環境中我們會遇到一些問題&#xff0c;此文主要記錄并復盤一下當時項目中的實際問題及解決過程。 背景簡述 最初系統上線后都比較正常風平浪靜的。在系統運行了一段時間后&#xff0c;業務量上升后&#xff0c;生產上發現java應用內存占用過高&#xff0c;服務器總共64…

打印出一個底部有n個*的漏斗c語言

題目描述 打印出一個底部有n個*的漏斗 輸入 第一行輸入一個T;表示有T組測試數據 下面每一行都有一個n表示漏斗底部*的個數 n保證是奇數 輸出 輸出打印結果 兩個測試答案之間要用換行分割 /*printf("這是第%d行 我要打印%d個* \n",Num,i); */ *********** *…

愛創科技總裁謝朝暉榮獲“推動醫藥健康產業高質量發展人物”

中國醫藥市場規模已經成為全球第二大醫藥市場&#xff0c;僅次于美國。近年來&#xff0c;隨著中國經濟的持續增長和人民生活水平的提高&#xff0c;醫藥市場需求不斷擴大。政府對醫療衛生事業的投入也在不斷加大&#xff0c;為醫藥行業的發展創造了良好的政策環境。為推動醫藥…

SparkSession介紹

一、 介紹 SparkSession是Spark 2.0中引入的新概念&#xff0c;它是Spark SQL、DataFrame和Dataset API的入口點&#xff0c;是Spark編程的統一API&#xff0c;也可看作是讀取數據的統一入口&#xff1b;它將以前的SparkContext、SQLContext和HiveContext組合在一起&#xff0…

結構體與指針_sizeof_static_extern_函數指針數組_函數指針_回調函數

一、結構體與指針 #include <stdint.h> #include <stdlib.h> #include <stdio.h> #define up_to_down(uuu) (downdemo_t *)(uuu->beg) #define __plc__ typedef struct updemo_s{uint8_t *head;uint8_t *beg;uint8_t *end; }updemo_t; typedef struct do…

陪玩圈子系統APP小程序H5,詳細介紹,源碼交付,支持二開!

陪玩圈子系統&#xff0c;頁面展示&#xff0c;源碼交付&#xff0c;支持二開&#xff01; 陪玩后端下載地址&#xff1a;電競開黑陪玩系統小程序&#xff0c;APP&#xff0c;H5: 本系統是集齊開黑&#xff0c;陪玩&#xff0c;陪聊于一體的專業APP&#xff0c;小程序&#xff…

2:kotlin集合(Collections)

集合有助于數據分組&#xff0c;方便后續操作 集合類型說明Lists有序的可重復的集合Sets無序的不可重復的集合Maps鍵值對映射集合&#xff0c;鍵唯一&#xff0c;且一個鍵只能映射到一個值 每個集合類型都可以是可變的或者只讀的 List List按照添加的順序存儲內容&#xff…

Linux進程通信——共享內存

概念 共享內存&#xff08;Shared Memory&#xff09;&#xff0c;指兩個或多個進程共享一個給定的存儲區。 特點 共享內存是最快的一種 IPC&#xff0c;因為進程是直接對內存進行存取。 因為多個進程可以同時操作&#xff0c;所以需要進行同步。 信號量共享內存通常結合在一…

Open3D (C++) 計算兩點云之間的最小距離

目錄 一、 算法原理二、代碼實現三、結果展示本文由CSDN點云俠原創,原文鏈接。如果你不是在點云俠的博客中看到該文章,那么此處便是不要臉的爬蟲與GPT。 一、 算法原理 Open3D中ComputePointCloudDistance函數提供了計算從源點云到目標點云的距離的方法,計算點云的距離。也…

python數據結構與算法-05_棧

棧 棧這個詞實際上在計算機科學里使用很多&#xff0c;除了數據結構外&#xff0c;還有內存里的棧區 &#xff08;和堆對應&#xff09;&#xff0c;熟悉 C 系語言的話應該不會陌生。 上一章我們講到了先進先出 queue&#xff0c;其實用 python 的內置類型 collections.deque …

【C語法學習】26 - strcmp()函數

文章目錄 1 函數原型2 參數3 返回值4 比較機制5 示例5.1 示例1 1 函數原型 strcmp()&#xff1a;比較str1指向的字符串和str2指向的字符串&#xff0c;函數原型如下&#xff1a; int strcmp(const char *str1, const char *str2);2 參數 strcmp()函數有兩個參數str1和str2&a…

HCIP-四、MUX-vlanSuper-vlan+端口安全

四、MUX-vlan&Super-vlan端口安全 MUX-vlan實驗拓撲實驗需求及解法1. 在SW1/2/3分別創建vlan10 20 30 402. SW1/2/3之間使用trunk鏈路&#xff0c;僅允許vlan10 20 30 40 通過。3. SW與PC/Server之間使用access鏈路。4. ping驗證&#xff1a; Super-vlan端口安全實驗拓撲實…

【騰訊云云上實驗室-向量數據庫】騰訊云開創新時代,發布全新向量數據庫Tencent Cloud VectorDB

前言 隨著人工智能、數據挖掘等技術的飛速發展&#xff0c;海量數據的存儲和分析越來越成為重要的研究方向。在海量數據中找到具有相似性或相關性的數據對于實現精準推薦、搜索等應用至關重要。傳統關系型數據庫存在一些缺陷&#xff0c;例如存儲效率低、查詢耗時長等問題&…

CentOS使用docker安裝OpenGauss數據庫

1.搜索OpenGauss docker search opengauss 2.選擇其中一個源拉取 docker pull docker.io/enmotech/opengauss 3.運行OpenGauss docker run --name opengauss --privilegedtrue --restartalways -d -e GS_USERNAMEpostgres -e GS_PASSWORDmyGauss2023 -p 5432:5432 docker.…

黑馬React18: ReactRouter

黑馬React: ReactRouter Date: November 21, 2023 Sum: React路由基礎、路由導航、導航傳參、嵌套路由配置 路由快速上手 1. 什么是前端路由 一個路徑 path 對應一個組件 component 當我們在瀏覽器中訪問一個 path 的時候&#xff0c;path 對應的組件會在頁面中進行渲染 2. …

2023年中國高壓驅動芯片分類、市場規模及發展趨勢分析[圖]

高壓驅動芯片是一種能在高壓環境下工作的集成電路&#xff0c;主要用于控制和驅動各種功率器件&#xff0c;如繼電器、電磁閥、電機、變頻器等。高壓驅動芯片根據其輸出電流的大小和形式可分為兩類恒流型和開關型。 高壓驅動芯片分類 資料來源&#xff1a;共研產業咨詢&#x…

藍橋杯算法雙周賽心得——迷宮逃脫(記憶化搜索)

大家好&#xff0c;我是晴天學長&#xff0c;非常經典實用的記憶化搜索題&#xff0c;當然也可以用dp做&#xff0c;我也會發dp的題解&#xff0c;需要的小伙伴可以關注支持一下哦&#xff01;后續會繼續更新的。&#x1f4aa;&#x1f4aa;&#x1f4aa; 1) .迷宮逃脫 迷官逃脫…