1. 程式人生 > 其它 >SpringBoot的淺淺配置和小整合

SpringBoot的淺淺配置和小整合

SpringBoot的淺淺配置和小整合

本文如題,就是淺淺記錄一下學習的過程中一些過程,比較簡單,並沒有多少深度。謝謝!

SpringBoot建立

  1. 從IDEA中新建專案或者模組。注意jdk版本,一般不超過你的環境jdk。

  2. 選擇要載入的依賴項。

SpringBoot的配置檔案

  1. SpringBoot的配置檔案可以用

    • application.properties
    • application.yml
    • application.yaml

    具體配置屬性可以到https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties檢視。

  2. 三種配置有優先關係,從.properties, .yml, .yaml優先關係遞減。但是又是互相層疊的。
    可以稍微舉個例子。比如:三個檔案都配置了埠號,那生效的就是按照優先順序來的。但是三個檔案都配置了獨有的配置,那這三個配置都會生效。

  3. 我們一般使用的是.yml,比較方便簡單。可以看看具體的配置例子。

    spring:
      datasource:
        druid:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=GMT%2B8&useSSL=false
          username: root
          password: root
    
  4. 在配置檔案中也可以使用屬性名引用方式引用屬性

    baseDir: /usr/local/fire
    center:
    dataDir: ${baseDir}/data
    tmpDir: ${baseDir}/tmp
    logDir: ${baseDir}/log
    msgDir: ${baseDir}/msgDir
    
  5. 我們可以使用@Value註解配合SpEL讀取單個數據,如果資料存在多層級,依次書寫層級名稱即可。

  6. 但是需要整體讀取上面的enterprise,就可以用@ConfigurationProperties這個註解

    • 新建一個類來封裝資料。
    @ConfigurationProperties(prefix = "enterprise")
    public class Enterprise {
    private String name;
    private Integer age;
    private String[] subject; 
    }
    
    
    
    • 再通過自動裝配,這樣就好了。

      @Autowired
      private Enterprise enterprise;
      

SpringBoot的一些小型整合

  1. 整合Junit

    • 預設IDEA的test下就有,觀察程式碼可以看到@SpringBootTest這個註解

    • 需要注意的是測試類如果存在於引導類所在包或子包中無需指定引導類

    • 測試類如果不存在於引導類所在的包或子包中需要通過classes屬性指定引導類。

      @SpringBootTest(classes = Springboot03JunitApplication.class)
      
  2. 整合Mybatis以及Druid

    • 首先需要匯入驅動和框架-

    • 然後配置屬性,這裡需要注意的是,由於匯入的驅動是8.x高版本,之前我用的5.x都是不需要配置時區的,但這裡需要配置時區。並且驅動也最好換成com.mysql.cj.jdbc.Driver,要不然會有一些小警告。

      spring:
        datasource:
          druid:
            driver-class-name: com.mysql.cj.jdbc.Driver
            url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=GMT%2B8&useSSL=false
            username: root
            password: root
      

後言

差不多水完了吧,後續可能要一段時間才能繼續學習相關知識了。大概到暑假才能繼續學習。

相關程式碼

CODE