- N +

spring boot入門代碼教程(springboot詳細入門)

大家好,今天小編來為大家解答以下的問題,關于spring boot入門代碼教程,springboot詳細入門這個很多人還不知道,現在讓我們一起來看看吧!

SpringBoot是如何動起來的

程序入口

SpringApplication.run(BeautyApplication.class,args);

執行此方法來加載整個SpringBoot的環境。

1.從哪兒開始?

SpringApplication.java

/**

*RuntheSpringapplication,creatingandrefreshinganew

*{@linkApplicationContext}.

*@paramargstheapplicationarguments(usuallypassedfromaJavamainmethod)

*@returnarunning{@linkApplicationContext}

*/

publicConfigurableApplicationContextrun(String...args){

//...

}

調用SpringApplication.java中的run方法,目的是加載SpringApplication,同時返回ApplicationContext。

2.執行了什么?

2.1計時

記錄整個SpringApplication的加載時間!

StopWatchstopWatch=newStopWatch();

stopWatch.start();

//...

stopWatch.stop();

if(this.logStartupInfo){

newStartupInfoLogger(this.mainApplicationClass)

.logStarted(getApplicationLog(),stopWatch);

}

2.2聲明

指定java.awt.headless,默認是true一般是在程序開始激活headless模式,告訴程序,現在你要工作在Headlessmode下,就不要指望硬件幫忙了,你得自力更生,依靠系統的計算能力模擬出這些特性來。

privatevoidconfigureHeadlessProperty(){

System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,System.getProperty(

SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,Boolean.toString(this.headless)));

}

2.4配置監聽并發布應用啟動事件

SpringApplicationRunListener負責加載ApplicationListener事件。

SpringApplicationRunListenerslisteners=getRunListeners(args);

//開始

listeners.starting();

//處理所有propertysources配置和profiles配置,準備環境,分為標準Servlet環境和標準環境

ConfigurableEnvironmentenvironment=prepareEnvironment(listeners,applicationArguments);

//準備應用上下文

prepareContext(context,environment,listeners,applicationArguments,printedBanner);

//完成

listeners.started(context);

//異常

handleRunFailure(context,ex,exceptionReporters,listeners);

//執行

listeners.running(context);

getRunListeners中根據type=SpringApplicationRunListener.class去拿到了所有的Listener并根據優先級排序。

對應的就是META-INF/spring.factories文件中的org.springframework.boot.SpringApplicationRunListener=org.springframework.boot.context.event.EventPublishingRunListener

private<T>Collection<T>getSpringFactoriesInstances(Class<T>type,

Class<?>[]parameterTypes,Object...args){

ClassLoaderclassLoader=Thread.currentThread().getContextClassLoader();

//Usenamesandensureuniquetoprotectagainstduplicates

Set<String>names=newLinkedHashSet<>(

SpringFactoriesLoader.loadFactoryNames(type,classLoader));

List<T>instances=createSpringFactoriesInstances(type,parameterTypes,

classLoader,args,names);

AnnotationAwareOrderComparator.sort(instances);

returninstances;

}

復制代碼

在ApplicationListener中,可以針對任何一個階段插入處理代碼。

publicinterfaceSpringApplicationRunListener{

/**

*Calledimmediatelywhentherunmethodhasfirststarted.Canbeusedforvery

*earlyinitialization.

*/

voidstarting();

/**

*Calledoncetheenvironmenthasbeenprepared,butbeforethe

*{@linkApplicationContext}hasbeencreated.

*@paramenvironmenttheenvironment

*/

voidenvironmentPrepared(ConfigurableEnvironmentenvironment);

/**

*Calledoncethe{@linkApplicationContext}hasbeencreatedandprepared,but

*beforesourceshavebeenloaded.

*@paramcontexttheapplicationcontext

*/

voidcontextPrepared(ConfigurableApplicationContextcontext);

/**

*Calledoncetheapplicationcontexthasbeenloadedbutbeforeithasbeen

*refreshed.

*@paramcontexttheapplicationcontext

*/

voidcontextLoaded(ConfigurableApplicationContextcontext);

/**

*Thecontexthasbeenrefreshedandtheapplicationhasstartedbut

*{@linkCommandLineRunnerCommandLineRunners}and{@linkApplicationRunner

*ApplicationRunners}havenotbeencalled.

*@paramcontexttheapplicationcontext.

*@since2.0.0

*/

voidstarted(ConfigurableApplicationContextcontext);

/**

*Calledimmediatelybeforetherunmethodfinishes,whentheapplicationcontexthas

*beenrefreshedandall{@linkCommandLineRunnerCommandLineRunners}and

*{@linkApplicationRunnerApplicationRunners}havebeencalled.

*@paramcontexttheapplicationcontext.

*@since2.0.0

*/

voidrunning(ConfigurableApplicationContextcontext);

/**

*Calledwhenafailureoccurswhenrunningtheapplication.

*@paramcontexttheapplicationcontextor{@codenull}ifafailureoccurredbefore

*thecontextwascreated

*@paramexceptionthefailure

*@since2.0.0

*/

voidfailed(ConfigurableApplicationContextcontext,Throwableexception);

}

3.每個階段執行的內容

3.1listeners.starting();

在加載SpringApplication之前執行,所有資源和環境未被加載。

3.2prepareEnvironment(listeners,applicationArguments);

創建ConfigurableEnvironment;將配置的環境綁定到SpringApplication中;

privateConfigurableEnvironmentprepareEnvironment(

SpringApplicationRunListenerslisteners,

ApplicationArgumentsapplicationArguments){

//Createandconfiguretheenvironment

ConfigurableEnvironmentenvironment=getOrCreateEnvironment();

configureEnvironment(environment,applicationArguments.getSourceArgs());

listeners.environmentPrepared(environment);

bindToSpringApplication(environment);

if(this.webApplicationType==WebApplicationType.NONE){

environment=newEnvironmentConverter(getClassLoader())

.convertToStandardEnvironmentIfNecessary(environment);

}

ConfigurationPropertySources.attach(environment);

returnenvironment;

}

3.3prepareContext

配置忽略的Bean;

privatevoidconfigureIgnoreBeanInfo(ConfigurableEnvironmentenvironment){

if(System.getProperty(

CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME)==null){

Booleanignore=environment.getProperty("spring.beaninfo.ignore",

Boolean.class,Boolean.TRUE);

System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME,

ignore.toString());

}

}

打印日志-加載的資源

BannerprintedBanner=printBanner(environment);

根據不同的WebApplicationType創建Context

context=createApplicationContext();

3.4refreshContext

支持定制刷新

/**

*RegisterashutdownhookwiththeJVMruntime,closingthiscontext

*onJVMshutdownunlessithasalreadybeenclosedatthattime.

*<p>Thismethodcanbecalledmultipletimes.Onlyoneshutdownhook

*(atmax)willberegisteredforeachcontextinstance.

*@seejava.lang.Runtime#addShutdownHook

*@see#close()

*/

voidregisterShutdownHook();

3.5afterRefresh

刷新后的實現方法暫未實現

/**

*Calledafterthecontexthasbeenrefreshed.

*@paramcontexttheapplicationcontext

*@paramargstheapplicationarguments

*/

protectedvoidafterRefresh(ConfigurableApplicationContextcontext,

ApplicationArgumentsargs){

}

3.6listeners.started(context);

到此為止,SpringApplication的環境和資源都加載完畢了;發布應用上下文啟動完成事件;執行所有Runner運行器-執行所有ApplicationRunner和CommandLineRunner這兩種運行器

//啟動

callRunners(context,applicationArguments);

3.7listeners.running(context);

觸發所有SpringApplicationRunListener監聽器的running事件方法

希望對你有幫助

springboot最后怎么被使用

創建獨立的Spring應用程序

2.嵌入的Tomcat,無需部署WAR文件

3.簡化maven配置

4.自動配置Spring

5.提供生產就緒型功能,如指標,健康檢查和外部配置

6.絕對沒有代碼生成并且對XML也沒有配置要求

springboot啟動原理流程

SpringBoot是SpringFramework的一個擴展,它簡化了Spring應用程序的開發和部署流程,并提供了一種快速創建可獨立運行Spring應用程序的方式。下面是SpringBoot啟動原理的簡單流程:

1.啟動類(MainClass)的加載

SpringBoot應用程序的啟動類是一個Java類,其中包含了main()方法,它是整個應用程序的入口。在啟動過程中,Java虛擬機(JVM)會首先加載該類。

2.SpringBoot環境的準備

在啟動類加載完成后,SpringBoot會在應用程序的classpath中查找application.properties或application.yml文件,讀取其中的配置信息,然后初始化Spring環境并創建ApplicationContext對象。此外,SpringBoot還會自動掃描所有帶有注解的類,并將它們注冊到Spring容器中。

3.SpringBoot的自動配置

SpringBoot具有一套智能的自動配置機制,可以根據應用程序所使用的依賴庫和配置文件自動配置SpringBean。例如,如果應用程序中引入了Hibernate,SpringBoot會根據Hibernate的依賴信息自動配置一個SessionFactoryBean。這樣,開發人員就無需手動配置這些Bean,可以更加專注于業務邏輯的實現。

4.SpringApplication的啟動

當SpringBoot環境準備好之后,就會創建一個SpringApplication對象。該對象負責啟動SpringBoot應用程序,并將所有Bean注冊到Spring容器中。它還可以接收并處理控制臺命令行參數,以及在應用程序啟動和關閉時執行一些回調方法。

5.實例化Web容器

如果應用程序是一個Web應用程序,則SpringBoot會自動實例化嵌入式Web服務器,如Tomcat、Jetty或Undertow等。SpringBoot將創建WebServer對象,并將所有Servlet、Filter和Listener注冊到其中。最后,Web容器會啟動,并開始監聽來自客戶端的HTTP請求。如果應用程序不是Web應用程序,則這一步可以略過。

6.應用程序啟動完成

當Web容器啟動之后,應用程序就開始監聽來自客戶端的HTTP請求,并根據配置文件中的路由規則進行處理。此時,應用程序已經啟動完成,并可以提供相關的服務。如果應用程序需要結束,可以通過調用SpringApplication對象的close()方法來關閉Spring容器和Web容器并釋放資源。

以上就是SpringBoot啟動原理的基本流程,整個過程涉及到了多個組件和技術點,包括Java虛擬機、SpringFramework、Web容器等。了解這些原理可以幫助開發者更好地理解和使用SpringBoot。

springboot條件查詢數據查不到

1.

數據庫連接配置錯誤:檢查MongoDB的連接地址、用戶名和密碼是否正確,并且確保已經正確地配置了MongoDB的數據庫名。

2.

查詢條件錯誤:檢查查詢條件是否正確,確保查詢的字段和值是正確的??梢酝ㄟ^打印日志或者在代碼中添加斷點來檢查查詢條件是否正確。

3.

數據庫中沒有符合條件的數據:檢查數據庫中是否存在符合查詢條件的數據。

責任鏈在spring boot 中的使用

在SpringBoot中,責任鏈模式可以通過使用攔截器(Interceptor)來實現。攔截器是Spring框架提供的一種機制,用于在請求處理過程中進行攔截和處理。

以下是在SpringBoot中使用責任鏈模式的一般步驟:

創建攔截器類:創建多個攔截器類,每個攔截器類負責處理特定的請求或業務邏輯。這些攔截器類應該實現Spring框架的HandlerInterceptor接口。

配置攔截器:在SpringBoot的配置類中,通過實現WebMvcConfigurer接口,并重寫addInterceptors方法來配置攔截器。在addInterceptors方法中,按照需要的順序添加攔截器。

定義攔截器執行順序:在配置攔截器時,可以通過實現Ordered接口或使用@Order注解來定義攔截器的執行順序。較小的值表示較高的優先級。

處理請求:當請求到達時,SpringBoot會按照配置的順序依次調用每個攔截器的preHandle、postHandle和afterCompletion方法。您可以在這些方法中編寫自定義的邏輯來處理請求。

通過以上步驟,您可以在SpringBoot中實現責任鏈模式,將請求傳遞給不同的攔截器進行處理。每個攔截器可以根據需要進行處理,或者將請求傳遞給下一個攔截器。

springboot log4j配置講解

在SpringBoot中,可以使用Log4j來進行日志記錄和管理。首先,需要在pom.xml文件中添加log4j的依賴。然后,在application.properties文件中配置log4j的相關屬性,如日志輸出路徑、日志級別等??梢允褂貌煌腁ppender來定義不同的日志輸出方式,如控制臺輸出、文件輸出等。還可以使用Logger來記錄日志,根據不同的日志級別進行記錄。通過合理配置log4j,可以方便地進行日志管理和調試。

OK,本文到此結束,希望對大家有所幫助。

返回列表
上一篇:
下一篇: