Spring Boot 2.0 讀書筆記_11:配置 Spring Boot

7. 配置 Spring Boot

寫在開頭,默認規則:啓動端口 8080;Web上下文訪問目錄 /
配置信息均可以在 application.properties 文件中配置

  • 基礎配置

    • Web監聽端口配置
      • application.properties:server.port=9090
      • 命令行指定啓動端口:java -jar bootsample.jar --server.port=9000
      • 虛擬機系統屬性:java -Dserver.port=9000 -jar bootsample.jar
    • Web上下文訪問目錄
      • server.servlet.context-path=/config
    • 綁定IP地址,適合多網卡環境
      • server.address
    • 設置會話過期時間,單位爲秒
      • server.session.timeout
    • 出錯處理路徑
      • server.error.path
    • Web服務器配置,內置Tomcat。也可以使用Jetty,Undertow
      • 引入Web服務器的starter依賴,以Undertow爲例。

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        
      • 剝除內置Tomcat依賴

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
          <exclusions>
              <exclusion>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-tomcat</artifactId>
              </exclusion>
          </exclusions>
        
      Undertow的性能要由於TomcatJetty,推薦使用。
  • 日誌配置
    默認情況下,Spring Boot 使用LogBack作爲日誌的實現,使用apache Commons Logging 作爲日誌接口。

    public class DemoController {
      private Log log = LogFactory.getLog(DemoController.class);
      //...
    }
    

    日誌格式舉例:

    2019-01-02 13:21:01.556  INFO 9884 
    --- 
    [  restartedMain] o.s.b.w.e.u.UndertowServletWebServer: 
    Undertow started on port(s) 9090 (http) with context path '/config'
    
格式 說明 備註
2019-01-02 13:21:01.556 日期和時間
INFO 日誌級別 ERROR、WARN、INFO、TRACE和DEBUG
關於日誌模塊可以查看以往博文:
https://blog.csdn.net/Nerver_77/article/details/82855061
9884 進程Id
分隔符號
[ restartedMain] 線程名稱
o.s.b.w.e.u.UndertowServletWebServer 所訪問的權限的類名
Undertow started on port(s) 9090 (http) with context path ‘/config’ 消息體 可以看出,運行在8090端口下,且上下文路徑配置爲"/config"

默認情況下,INFO級別以上的信息纔會打印到控制檯,也可以自定義日誌輸出級別。

logging.level.root=info
logging.level.org.springframework=info
# 日誌輸出路徑及文件
logging.path:e:/temp/log
logging.file = my.log

當日志文件大小達到 10MB 的時候,會自動重新生成一個新的日誌文件,同時還可以對日誌輸出和文件輸出進行格式控制。(僅適用內置的logback)

logging.pattern.console=%level %date{HH:mm:ss} %logger{20}.%M %L :%m%n
logging.pattern.file= %level %date{ISO8601} [%thread]  %logger{20}.%M %L :%m%n
格式 說明
%level 輸出日誌級別
%date 日誌記錄時間
{ISO8601}標準日誌格式輸出
{yyyy-MM-dd HH:mm:ss.SSS}
%logger 用於輸出Logger名字(包名 + 類名)
{n}限制輸出長度
原則上儘可能顯示類名、壓縮包名
%thread 當前線程名
%M 日誌發生時的方法名稱
%L 日誌調用所在的代碼行(線上運行不建議使用)
%m 日誌信息
%n 日誌換行
  • 讀取應用配置:從配置文件 application.properties 讀取內容

    • 通用 Environment類
      Environment 是一個通用的讀取應用程序運行時的環境變量的類,可以讀取 application、properties、命令行輸入參數、系統屬性、操作系統環境變量等。同時,Environment 是 Spring Boot 最早初始化的一個類。

      @Configuration
      public class EnvConfig implements BeanPostProcessor {
      
          // Spring 容器自動注入
          @Autowired
          private Environment env;
      
          public int getServerPort() {
              return env.getProperty("server.port", Integer.class);
          }
      }
      
      讀取 返回值
      env.getProperty(“user.dir”) 程序運行的目錄,IDE中工程目錄
      user.dir是系統屬性
      env.getProperty(“user.home”) 執行程序的用戶的home目錄
      user.home是系統屬性
      env.getProperty(“JAVA_HOME”) 讀取設置的環境變量(不區分大小寫)
    • @Value 註解獲取
      直接通過 @Value 註解注入配置信息到 Spring 管理的 Bean 中:

      @Value("${server.port}")
      Integer port;
      

      注意,@Value 並不能在任何 Spring 管理的 Bean 中使用,因爲 @Value 本身是通過 AutowiredAnnotationBeanPostProcessor 實現的。[BeanPostProcessor接口的實現類]
      @Value 註解支持 SpEL 表達式,如果屬性不存在,可以提供默認值:

      @Value("${cache.enable:false}")
      private boolean isCache;
      
    • @ConfigurationProperties
      通常情況下,將一組同樣類型的配置屬性映射爲一個類更爲方便,比如服務器配置。

        server.port=9090
        server.context-path=/config
      

      以上配置都是與 Web 服務器配置相關,都有 server 前綴。因此可以使用 @ConfigurationProperties 來獲取該前綴配置。

      @ConfigurationProperties("server")
      @Configuration
      public class ServerConfig {
          private int port;
          private String contextPath;
      }
      

      在處理被 @ConfigurationProperties 註解的類,會自動將 -_,轉化爲Java的命名規範(駝峯式)

  • 自動裝配
    Spring 容器的配置核心就是使用 @Configuration 作用在類上,並且聯合在此類採用 @Bean 註解的方法,聲明 Spring 管理的 Bean。

    @Configuration
    public class MyConfiguration {
        @Bean
        public TestBean getBean() {
            return new TestBean();
        }
    }
    

    如上代碼中,MyConfiguration 類使用了註解 @Configuration ,向 Spring 表明這是一個配置類,類裏面所有帶 @Bean 註解的方法都會被 Spring 調用,返回對象將作爲一個 Spring 容器管理的 Bean。

  • Bean 條件裝配
    Spring Boot可以通過有無指定Bean來決定是否配置Bean。使用@ConditionalOnBean,在當前上下文中存在某個對象是,纔會實例化一個Bean;使用@ConditionalOnMissingBean,在當前上下文中不存在某個對象時,纔會實例化一個Bean。

    @Configuration
    // 該配置類生效的前提是:上下文中已經配置了 DataSource。
    @ConditionalOnBean(DataSource.class)
    public class MyConfig {}
    
  • Class 條件裝配
    Class 條件裝配是按照某各類是否在Classpath中決定是否要配置Bean。@ConditionalOnClass 標識當 classpath 有指定的類時,配置生效。

    @Configuration
    @ConditionalOnClass(JestClient.class)
    public class JestAutoConfiguration {}
    

    這段代碼用於配置 Elasticsearch,使用 Jest 驅動,因此配置生效的前提條件是 classpath 中有 JestClient.class 類。

  • Environment 裝配

    @ConditionalOnProperty(prefix = "ces", name = "message.enabled", havingValue = "true", matchIfMissing = true)
    public class MsgConfig {}
    

    @ConditionalOnProperty 註解根據prefix + name (前綴和名稱)來讀取Environment的變量包含屬性(K-V),根據其值與 havingValue值作比較決定配置是否生效 [ 默認不爲false即爲生效 ]。matchIfMissingtrue 意味着如果 Environment 沒有包含該前綴和名稱的配置也可生效 [默認爲false]。

  • 其他條件裝配

    • @ConditionalOnExpression,當表達式爲 true 時,纔會實例化一個 Bean,支持SpEL表達式。

    • @ConditionalOnJava,指定Java版本,如下栗子:

       @ConditionalOnJava(range = Range.EQUAL_OR_NEWER, value = JavaVersion.EIGHT)
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章