1. 程式人生 > 其它 >SpringBoot 從入門到原始碼解析

SpringBoot 從入門到原始碼解析


快速入門

  • 建立 Maven 工程,引入依賴

    <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.4.5</version>
    </parent>
    
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
    </dependencies>
    
  • 建立主程式,執行main函式,瀏覽器直接訪問。

    //啟動類
    @SpringBootApplication
    public class Springboot01Application {
    
      public static void main(String[] args) {
          SpringApplication.run(Springboot01Application.class, args);
      }
    }
    
    //Controller控制層
    @RestController
    public class HelloController {
      @RequestMapping("/hello")
      public String hello(){
          return "hello spring boot";
      }
    }
    
  • 簡化配置:唯一配置檔案 application.properties

  • 簡化部署:打包外掛,打成jar包

    <build>
      <plugins>
        <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
      </plugins>
    </build>
    

原理分析

  • 依賴管理

    • 父專案做依賴管理,版本控制。
    • 更改版本
    • starter場景啟動器
  • 自動配置

    • 我們自己寫的Controller、Service、Dao都必須在啟動類的包內或者子包,這樣就會自動掃描包。

    • 引入spring boot starter依賴,啟動主程式,之前xml中的元件都被自動配置了,一共127個,但是因為條件裝配(@Conditional),最終會按需配置。



    • 配置檔案的配置最終都對應一個類,這些類會在容器中建立物件。


註解使用

  • @Conditional:滿足條件則進行元件注入

  • @ImportResource:匯入Spring配置檔案XML中配置的bean

  • @ConfigurationProperties:配置繫結,讀取properties檔案內容,封裝到bean


作者湊數的園丁

出處https://www.cnblogs.com/lq-404/

版權宣告: 本部落格所有文章除特別宣告外,均採用 BY-NC-SA 許可協議。轉載請註明出處!

聲援博主: 如果您覺得文章對您有幫助,可以點選文章右下角【推薦】一下。