日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

Spring Applications

SpringApplication: 提供一種便攜的方式來啟動Spring應用(main函數)。 可以使用靜態方法調用 SpringApplication.run

啟動

啟動日志

  1. Spring啟動日志默認為info級別,可以關閉 spring.main.log-startup-info=false
  2. FailureAnalyzers 處理啟動時拋出的異常,可以自己實現
  3. 若仍無analyzer處理異常,則可以使用DEBUG級別的日志,或者啟動時增加debug屬性:
  4. JAVA -jar *.jar --debug

延遲加載

  1. 延遲加載默認關閉,開啟有可能導致錯誤延后發現
  2. 延遲加載開關配置: spring.main.lazy-initialzation=true
  3. 延遲開關代碼: SpringApplicationBuilder lazyInitialization; SpringApplication setLazyInitialization
  4. 延遲開關注解: @Lazy(false)

banner

  1. 類: SpringBootBanner
  2. 配置文件 banner.txt
  3. 支持將系統的一些變量輸出
  4. 代碼設置: SpringApplication.setBanner()
  5. 開關配置 console/log/off: spring.main.banner-mode=off
  6. 地址配置:spring.banner.location

自定義Spring Application

  1. 支持自定義SpringApplication
  2. @SpringBootApplication
    public class MyApplication { public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.setBannerMode(Banner.Mode.OFF); application.run(args); }}

Builder API

  1. Springboot應用構建
  2. new SpringApplicationBuilder()
    .sources(Parent.class) .child(Application.class) .bannerMode(Banner.Mode.OFF) .run(args);

應用可用性監控

  1. Spring boot actuator
  2. ApplicationAvailability 實現該接口來向外暴露狀態

Liveness State

應用是否存活,與外部狀態無關

Readiness State

應用是否可用(例如CommandLineRunner ApplicationRunner在被執行時)

狀態管理

  • 監聽狀態改變
  • @Component
    public class MyReadinessStateExporter { @EventListener public void onStateChange(AvailabilityChangeEvent<ReadinessState> event) { switch (event.getState()) { case ACCEPTING_TRAFFIC: // create file /tmp/healthy break; case REFUSING_TRAFFIC: // remove file /tmp/healthy break; } }}
  • 改變狀態
  • @Component
    public class MyLocalCacheVerifier { private final ApplicationEventPublisher eventPublisher; public MyLocalCacheVerifier(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void checkLocalCache() { try { // ... } catch (CacheCompletelyBrokenException ex) { AvailabilityChangeEvent.publish(this.eventPublisher, ex, LivenessState.BROKEN); } }}

應用事件監聽

除了通常的Spring事件, 比如ContextRefreshedEvent, SpringApplication還可以發送其他事件

有些事件在ApplicationContext創建之前觸發,這種無法通過注冊bean來注冊監聽器,可以通過其他方式監聽:
SpringApplication.addListeners()/ SpringApplication.listeners()

支持自動化配置listeners. META_INF/spring.factories

org.springframework.context.ApplicationListener=com.example.MyListener

應用實踐發送順序:

  1. An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
  2. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.
  3. An ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
  4. An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.
  5. An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.
  6. An AvailabilityChangeEvent is sent right after with LivenessState.CORRECT to indicate that the application is considered as live.
  7. An ApplicationReadyEvent is sent after any application and command-line runners have been called.
  8. An AvailabilityChangeEvent is sent right after with ReadinessState.ACCEPTING_TRAFFIC to indicate that the application is ready to service requests.
  9. An ApplicationFailedEvent is sent if there is an exception on startup.

當ApplicationContext 被刷新后會觸發ContextRefreshedEvent

實現ApplicationContextAware 可注入ApplicationContext

獲取啟動參數

ApplicationArguments

@Component
public class MyBean {

  public MyBean(ApplicationArguments args) {
      boolean debug = args.containsOption("debug");
      List<String> files = args.getNonOptionArgs();
      if (debug) {
          System.out.println(files);
      }
      // if run with "--debug logfile.txt" prints ["logfile.txt"]
  }

}

ApplicationRunner CommandLineRunner

在SpringApplication啟動之后, 需要運行相關代碼時, 可以用ApplicationRunner或CommandLineRunner。 接口均實現run方法。 區別是ApplicationRunner使用ApplicationArguments, CommandLineRunner使用字符串數組接收請求參數。

若有多個bean被定義并要求有順序執行,可以實現
org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order

應用關閉

每個Spring應用會向JVM注冊一個鉤子確保ApplicationContext可以順利關閉 每個標準Spring生命周期的方法會被調用(例如DisposableBean 或@PreDestroy)

可以指定錯誤碼
org.springframework.boot.ExitCodeGenerator(自定義異常錯誤碼)

SpringApplicaiton.exit()

管理特性

啟動管理功能,支持遠程管理,暴露
SpringApplicationAdminMXBean MBeanServer

spring.application.admin.enabled=true

外部配置

包含Java properties files, yaml files, environment variables, command-line arguments

可通過@Value獲取 或者 結構化對象(通過@ConfigurationProperties)

@value(${name:123})

配置優先級

  1. Default properties (specified by setting SpringApplication.setDefaultProperties).
  2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.
  3. Config data (such as application.properties files).
  4. A RandomValuePropertySource that has properties only in random.*.
  5. OS environment variables.
  6. Java System properties (System.getProperties()).
  7. JNDI attributes from java:comp/env.
  8. ServletContext init parameters.
  9. ServletConfig init parameters.
  10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
  11. Command line arguments.
  12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
  13. @TestPropertySource annotations on your tests.
  14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.

配置文件按以下優先級覆蓋

  1. Application properties packaged inside your jar (application.properties and YAML variants).
  2. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants).
  3. Application properties outside of your packaged jar (application.properties and YAML variants).
  4. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants).

可通過命令行設置配置

使用 -- 前綴

關閉命令行參數
SpringApplication.setAddCommandLineProperties(false)

通過json配置

環境變量: SPRING_APPLICATION_JSON java 啟動命令: -Dspring.application.json

外部配置

通過以下順序:

  1. classpath
    1. classpath
    2. classpath/config
  2. current dir
    1. current dir
    2. current dir/config

修改配置文件名稱 Java啟動命令 --spring.config.name=···

修改配置文件地址 --spring.config.location
--spring.config.additional-location

配置文件地址支持使用通配符* , 支持多個目錄配置文件

環境配置文件 application-{profile}

外部導入

支持外部導入配置文件

spring.config.import=optional:file:./dev.properties

若不支持后綴名可以換寫法:

spring.config.import=optional:file:./dev[.ymal]

配置樹

可支持按文件層級關系做配置

spring.config.import=optional:configtree:/etc/config

占位符

可使用其他配置作為變量 ${app.name}

配置中的隨機變量

支持integer, long, uuid, strings.

${random.value}
${random.int}
${random.long}
${random.uuid}
${random.int(10)}
${random.int[1024, 65536]}

類型安全的配置(使用類配置)

@ConfigurationProperties("") 注意還需要作為一個bean來注入使用

Profiles

任何@Comp.NET, @Configuration, @ConfigurationProperties都可以被@Profile限制。

指定激活profile

spring.profiles.active=dev,hsqldb

spring.profiles.default=none

profile group

profiles

spring.profiles.group.production[0]=proddb
spring.profiles.group.production[1]=prodmq

程序設置profile

SpringApplication.setAdditionalProfiles(...)

Logging

日志格式

  • Date and Time: Millisecond precision and easily sortable.
  • Log Level: ERROR, WARN, INFO, DEBUG, or TRACE.
  • Process ID.
  • A --- separator to distinguish the start of actual log messages.
  • Thread name: Enclosed in square brackets (may be truncated for console output).
  • Logger name: This is usually the source class name (often abbreviated).
  • The log message.

日志顏色

%clr 來指定日志顏色

%clr(%5p)
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}

顏色支持: blue,cyan,faint,green,magenta,red,yellow

文件輸出

日志文件為10MB, 默認輸出ERROR, WARN, INFO logging.file.name logging.file.path

file rotation

  • logging.logback.rollingpolicy.file-name-pattern
  • The filename pattern used to create log archives.
  • logging.logback.rollingpolicy.clean-history-on-start
  • If log archive cleanup should occur when the application starts.
  • logging.logback.rollingpolicy.max-file-size
  • The maximum size of log file before it is archived.
  • logging.logback.rollingpolicy.total-size-cap
  • The maximum amount of size log archives can take before being deleted.
  • logging.logback.rollingpolicy.max-history
  • The maximum number of archive log files to keep (defaults to 7).

日志等級

日志級別: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF

logging.level.<logger-name>=<level>
logging.level.root=

日志組

spring有預設的日志組 如 web, sql

logging.group.Tomcat=org.Apache.catalina,org.apache.coyote,org.apache.tomcat

logging.level.tomcat=trace

日志關閉鉤子

logging.register-shutdown-hook=false

自定義日志配置

指定自定義日志系統

org.springframework.boot.logging.LoggingSystem=

logback: logback-spring.xml, logback.xml

log4j2: log4j2-spring.xml, log4j2.xml

JDK: logging.properties

分享到:
標簽:Spring Boot
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定