Springboot 筆記

1.微服務:一個項目 可以由多個 小型服務構成(微服務)
2.spring boot可以快速開發 微服務模塊
    a.簡化j2ee開發
    b.整個spring技術棧的整合(整合springmvc  spring)    
    c.整個j2ee技術的整合(整合mybatis redis)

            
3準備:
jdk:
    JAVA_HOME: jdk根目錄
    path:jdk根目錄\bin
    classpath: .;jdk根目錄\lib
maven:
    MAVEN_HOME: maven根目錄
    path: maven根目錄\bin
    配置Maven本地倉庫:  mvn根目錄/conf/setting.xml : <localRepository>D:/mvnrep</localRepository>
    在IDE中配置mvn:
        window->preference->搜maven ,installations/user settings
    

4spring boot開發工具:
    Eclipse(STS插件) -》STS
    IntelliJ IDEA
    

5目錄結構resources:
    static:靜態資源(js css 圖片 音頻 視頻)
    templates:模板文件(模版引擎freemarker ,thymeleaf;默認不支持jsp)
    application.properties: 配置文件
    

6spring boot內置了tomcat,並且不需要打成war再執行。
可以在appication.properties對端口號等服務端信息進行配置

    spring boot將各個應用/三方框架 設置成了一個個“場景”stater,
 以後要用哪個,只需要引入那個場景即可。
選完之後,spring boot就會將 該場景所需要的所有依賴 自動注入。 
例如 選擇 “web”,spring boot就會將web相關的依賴(tomcat  json) 全部引入本項目
    
7
    @SpringBootApplication:spring boot的主配置類
    該註解包含:
    @SpringBootConfiguration: 包含@Configuration,表示“配置類”: 
                                1.該類是一個配置類    
                                2.加了@Configuration註解的類,會自動納入Spring 容器  (@Component)

@Configuration
public class A//表示A是一個 用於 配置的類
{
}

    @EnableAutoConfiguration:使spring boot可以自動配置 :可以找到@SpringBootApplication所在類的包 ,作用:就會將該包及所有的子包 全部納入spring容器
    spring boot在啓動時,會根據META-INF/spring.factories找到相應的三方依賴,並將這些依賴引入本項目

    總結:
    編寫項目時,一般會 對自己寫的代碼  以及 三方依賴 進行配置。但是spring boot可以自動進行配置:
      a:自己寫的代碼,spring boot通過@SpringBootConfiguration自動幫我們配置;
      b. 三方依賴 通過spring-boot-autoconfigure-2.0.3.RELEASE.jar中
         的META-INF/spring.factories進行聲明,然後通過@EnableAutoConfiguration開啓使用即可
    spring-boot-autoconfigure-2.0.3.RELEASE.jar包中 包含了 J2EE整合體系中 需要的依賴。
     c.如何自動裝配:
        研究org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
        通過觀察該源碼 發現:
        @Configuration:標識此類是一個配置類  、將此類納入springioc容器
        @EnableConfigurationProperties(HttpEncodingProperties.class): 通過HttpEncodingProperties將編碼設置爲了UTF_8 (即自動裝配爲UTF_8, 如何修改改編碼:通過改HttpEncodingProperties的 predfix+屬性名 進行修改 [配置文件中,yml/properties])
           即:該註解給了默認編碼utf8,並且提供了prefix+屬性名 的方式 供我們修改編碼。


        @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
        當屬性滿足要求時,此條件成立  :要求 如果沒有配置spring.http.encoding.enabled=xxx, 則成立。
    
    總結:1每一個XxAutoConfiguration 都有很多條件@ConditionalOnXxx,當這些條件都滿足時,
    則此配置自動裝配生效(utf-8)。但是我們可以手工修改改 自動裝配: XxxProperties文件中的  
    prefix.屬性名=value 
          2全局配置文件中的key, 來源於某個Properties文件中的 prefix+屬性名
        --boot通過XxAutoConfiguration實現自動裝配 ,修改默認值 XxxProperties( prefix+屬性名)
             
        如何直到 spring boot開啓了哪些自動裝配、禁止了哪些自動裝配: application.properties中 debug=true
        Positive matches列表 表示 spring boot自動開啓的裝配
        Negative matches列表 表示spring boot在此時 並沒有啓用的自動裝配。
        
    

自己寫的
引入三方依賴(jar、配置)

8.配置文件
    作用:spring boot 自動配置(約定,8080 ).可以使用配置文件 對默認的配置 進行修改

默認全局配置文件:
    application.properties  : k=v,或行內寫法(k: v,[Set/List/數組] {map,對象類型的屬性},並且 []可省,{}不能省)
    application.yml  :  yaml ain't myarkup language ,不是一個標記文檔
    注意:1. k:空格v   2.通過垂直對齊 指定層次關係    3.默認可以不寫引號; ""會將其中的轉義符進行轉義,其他不會

    
    server:
        port: 8882
        path: /a/b/c

    xml:是一個標記文檔
        <server>

            <port>8882</port>
            <path>/a/b/c</path>
        </server>


9.通過yaml給對象注入值:
注入值
yaml:
student:
  #name: zs
  #age: 23
  sex: true
  birthday: 2019/02/12
    
綁定:
@Component //將此Javabean
@ConfigurationProperties(prefix="student")
public class Student 
    

綁定:    @ConfigurationProperties(yml/properties)    @Value("xx") 二者可以互補

        @ConfigurationProperties    @Value
注值        批量注入                單個
鬆散語法        支持                不支持
SpEL        不支持                支持
JSR303數據校驗    支持                不支持
注入複雜類型    支持                不支持


簡單類型:(8個基本類型/String/Date)


10.@PropertySource:默認會加載application.properties/application.yml文件中的數據;
    例如@PropertySource(value={"classpath:conf.properties"})加載conf.properties文件中的數據;
    但是,@PropertySource只能加載properties,不能加載yml

11.@ImportResource
    spring boot自動裝配/自動配置.
    spring等配置文件  默認會被spring boot自動給配置好。
    如果要自己編寫spring等配置文件, spring boot能否識別?  默認不識別。 
如果需要識別,則需要在spring boot主配置類上 通過@ImportResource指定配置文件的路徑
    
    但是不推薦手寫spring配置文件。
    配置:xml配置文件,通過註解配置。
    spring boot推薦使用註解方式進行配置:寫類,@Configuration  @Bean ,示例:
//配置類(等價於spring.xml)
@Configuration
public class AppConfig {
    @Bean        
    public StudentService stuService(){//<bean  id="xxxxxxxxxxxxx">
        StudentService stuService = new StudentService();
//        
//        StudentDao stuDao = new StudentDao()  ;
//        stuService.setStudentDao(stuDao);
        
        return stuService;//返回值 <bean  class="xxxxxxxxxxxxx">
    }
}

12.spring boot全局配置文件中的 佔位符表達式
a.隨機數 ${random.uuid}等
b.引用變量值 
    yml中:
    student:
          name: ${student.user.name}

    實際引用的是properties中的student.user.name=zl67


    yml中:
    student:
          name: ${student.user.name2:無名}
13.多環境的切換(profile)
    a. properties
    默認boot會讀取application.properties環境8882
    多個:
    application-環境名.properties
    application-dev.properties8883
    application-test.properties8884

    如果要選擇某一個具體的環境: application.properties中指定:spring.profiles.active=環境名

    如果將application.properties註釋掉,spring boot仍然會讀取其他appilcation-環境名.properties中的配置。並且properties的優先級高於yml
    用————區分

    b.yml
    第一個環境(主環境)
    server:
          port: 8883
    spring:
          profiles:
                active: dev  指定本次採用的環境
    第二個環境
    ---
    server:
        port: 8884
    spring:
         profiles: dev  環境名

    c.動態切換環境
         i:通過運行參數指定環境
        (1)STS(Eclipse) :Run Configuration - Argument - program Argument    
            --spring.profiles.active=環境名
         (2)命令行方式:
            java -jar 項目名.jar --spring.profiles.active=環境名
        ii:通過vm參數指定環境
            STS(Eclipse) :Run Configuration - Argument - VM    
            -Dspring.profiles.active=環境名

13.配置文件的位置

    i.項目內部的配置文件:
    properties和yml中的配置,相互補充;如果衝突,則properties優先級高。
    spring boot默認能夠讀取的application.properties/application.yml,這2個文件 可以存在於以下4個地方:
    file:項目根目錄/config         application.properties
    file:項目根目錄            application.properties
    classpath:項目根目錄/config    application.properties
    classpath:項目根目錄        application.properties
    
    注意:            
    a.如果某項配置衝突,則優先級從上往下
    b.如果不衝突,則互補結合使用

     配置項目名:
    properties文件中
    server.servlet.context-path=/boot

    ii.項目外部的配置文件: (補救)
    在項目Run configuration ,argumenets:
    --spring.config.location=D:/application.properties
    如果 同一個配置 同時存在於 內部配置文件 和外部配置文件,則外部>內部
    
    HW.jar   運行,8881--8882
    外部配置文件
    通過命令行 調用外部配置文件
    java -jar  項目.jar  --spring.config.location=D:/application.properties

    iii.項目運行參數: (補救)
    在項目Run configuration ,argumenets:
    --server.port=8883
    通過命令行 調用外部配置文件
    java -jar  項目.jar  --server.port=8883

    多個地方配置時,如果衝突,優先級:
    命令參數(調用外部的配置文件 > 運行參數 )>內部文件 (properties>yaml)

    官網對多配置時的順序說明:https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#boot-features-external-config

14.日誌
    日誌框架 UCL  JUL  jboss-logging,logback,log4j,log4j2,slf4j...
    spring boot默認選用slf4j,logback
    spring boot默認幫我們配置好了日誌,我們直接使用即可。
    日誌級別:
        TRACE< DEBUG< INFO<WARN< ERROR< FATAL<OFF

    springboot默認的日誌級別是info(即只打印  info及之後級別的信息);也可以自定義級別:全局配置文件中logging.level.org.yq.HelloWorld=warn ,即logging.level.主配置類所在包=級別

    可以通過配置 將日誌信息 存儲到文件中 logging.file=springboot.log  存儲到了項目的根目錄中的springboot.log
    也可以指定 具體的日誌路徑:logging.file=D:/springboot.log

    也可以存儲到一個 文件夾中 ,logging.path=D:/log/,並且默認的文件名是spring.log

    指定日誌顯示格式:
        a.日誌顯示在console中
            logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
                    %d:日期時間
                    %thread:線程名
                    %-5level: 顯示日誌級別,-5表示從左顯示5個字符寬度
                    %logger{50} :設置日誌長度  ,例如o.s.w.s.m.m.a.

                    %msg:日誌消息
                    %n :回車
        b.日誌顯示在文件中
            logging.pattern.file=%d{yyyy-MM-dd} ** [%thread] ** %-5level ** %logger{50}** %msg%n

            
    默認的日誌格式,是在 jar包中 相應包的xml文件中進行配置。
    日誌的具體使用規範:官方說明https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#boot-features-custom-log-configuration

15.springboot開發Web項目 (靜態資源 html css js  )
    
    new - spring starer -設置(選擇 需要的場景,web)

    spring boot是一個jar,因此 靜態資源就不是再存放到 webapps中, 存放在哪裏?
    靜態資源的存放路徑 通過WebMvcAutoConfiguration類-addResourceHandlers()指定:/webjars/
    spring boot將靜態資源存入到jar包中,引入: 從Jar目錄結構的webjars開始寫:http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js
    
    如何自己寫 靜態資源,如何放到如spring boot中?  將自己寫的 靜態資源->jar,同上(不推薦);
    推薦:spring boot約定: spring boot將一些目錄結構 設置成靜態資源存放目錄,  我們的靜態資源直接放入這些目錄即可 。目錄在哪裏? ResourceProperties類中的CLASSPATH_RESOURCE_LOCATIONS中設置:
     {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" 
     }
     注意:在以上目錄存放資源文件後,訪問時  不需要加前綴,直接訪問即可:http://localhost:8080/world.html

    設置歡迎頁:
    WebMvcAutoConfiguration類中的welcomePageHandlerMapping() -->getIndexHtml() --> location + "index.html" ,即 任意一個靜態資源目錄中的 Index.html就是歡迎頁
    
    網站中  網頁標籤的Logo是固定名字  : favicon.ico
    自定義 favicon.ico  :閱讀 源碼得知 :只需要將  favicon.ico文件 放入 任意靜態資源目錄中即可。
        
    總結:1.通過源碼發現靜態資源的目錄    2.用靜態資源:只需要將靜態資源放入 以上目錄即可
          3. 其他特定的文件(歡迎頁、ico),只需要 根據約定(index.html  favicon.ico)  放入該目錄即可
    
    
    如何自定義靜態資源目錄(Properties文件中的 prefix+屬性) :
            spring.resources.static-locations=classpath:/res/, classpath:/img/

    以上就將 靜態資源目錄設置爲了classpath:/res/, classpath:/img/ ,注意 自定義靜態資源目錄後  以前默認的目錄會失效

    
    動態資源:  JSP(spring boot默認不支持)
           推薦:模板引擎 thymeleaf
           網頁= 模板+數據

    引入thymeleaf:到官網查詢 thymeleaf的依賴(Maven)
    

    使用thymeleaf:代碼在哪裏寫?
        ThymeleafAutoCongifutation 、
        XxProperties
    通過ThymeleafProperties源碼得知:
    使用thymeleaf只需要將 文件放入目錄:"classpath:/templates/";  文件的後綴: ".html";
    
    注意:在以前傳統的web項目中:靜態資源修改後  是不需要重啓的;但是在spring boot項目中,修改後 需要重啓。
        
    

        <p th:text="${welcome}">welcome to thymeleaf....</p>以上,先從${welcome}中取值,如果有 則直接顯示;如果沒有,則在顯示welcome to thymeleaf....
    
        th就是替換原有html的值:th:html屬性名=值 ;
        <p id="pid" class="pclass"  th:id="${welcome}" th:class="${welcome}"  th:text="${welcome}">welcome to thymeleaf....</p>

        th:xx  (參見第10章  Attrubite Pre....)
        th:text      獲取文本值       顯示 將hello 渲染爲h1後的效果
        th:utext  獲取文本值(不轉義) 顯示<h1>hello</h1>

        符號
        th:text="${welcome}" ,除了$以外  其他符號? 查看第四章  Standard Express....

        
16.Spring boot整合JSP開發
    之前spring boot默認 自帶一個內置的tomcat,不需要打war包,直接通過Jar即可運行。


    但是,如果要整合jsp開發,就需要 單獨配置一個 外置的tomcat ,需要打war包。
    Spring boot整合JSP開發步驟:
        1.新建boot項目, war        
            注意:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
                provided:意思是 將項目打包時,不需要將內置的tomcat一起打包。

        2.建立基本的web項目所需要的目錄結構
            webapps/WEB-INF(需要)
            webapps/WEB-INF/web.xml (不需要)
            webapps/index.jsp
        3.創建tomcat實例、部署項目    
        訪問:
        域名:端口/項目名/文件名
        http://localhost:8080/SbJSP/index.jsp


        分析:
        如果是一個war包的spring boot項目,在啓動服務器tomcat時, 會自動調用ServletInitializer類中 的configure方法,configure方法會調用spring boot的主配置類 從而啓動spring boot;
        即在啓動tomcat服務器時  會1啓動tomcat  2啓動spring boot


    
        

        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章