1. 程式人生 > >不學無數——SpringBoot入門Ⅱ

不學無數——SpringBoot入門Ⅱ

SpringBoot

1.Starters

Starters是一套技術,是什麼技術呢?是SpringBoot整理出來,人們經常要用的技術。有了starters人們在想要使用這些技術的時候,就不用扒之前的老程式碼將那些依賴啊或者配置的都拷貝過來,只需要加上SpringBoot提供的依賴就行,它自動會進行依賴管理。例如,如果你想在SpringBoot專案中整合JPA,那麼只需要在引入jar包的地方加上spring-boot-starter-data-jpa即可,SpringBoot會自動將其和其他所依賴的包載入進專案中。

所有SpringBoot提供的Starters命名都有一套規則,spring-boot-starter-*

,其中的*就是你想要引用的技術的名稱。

下面列一些Starters

名稱 描述
spring-boot-starter SpringBoot的核心,其中提供了自動配置的支援,日誌,以及YAML
spring-boot-starter-activemq 提供對於ActiveMq的使用的支援
spring-boot-starter-amqp 對於Spring AMQP和RabbitMQ的支援
spring-boot-starter-aop 對於Spring面向切面程式設計的支援
spring-boot-starter-web 初始化關於Web啟動的一些東西,另外支援RESTful,支援SpringMvc,使用tomcat為預設的內嵌容器

在這就簡單介紹這幾個Starters,想看具體介紹的可以參考SpringBootg官方文件

2.自定義啟動頁面

在專案啟動的時候,在列印日誌的上面會有一個影象,這個就是啟動的時候自動載入的。就像下面這樣初始影象是這樣的。

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.7.RELEASE)

2018-07-16 10:18:03.591  INFO 4737 --- [           main] c.e.F.FirstSpringBootApplication         : Starting FirstSpringBootApplication on hupengfeideMacBook-Pro.local with PID 4737 (/Users/hupengfei/mygit/FirstSpringBoot/out/production/classes started by hupengfei in /Users/hupengfei/mygit/FirstSpringBoot)
2018-07-16 10:18:03.595  INFO 4737 --- [           main] c.e.F.FirstSpringBootApplication         : No active profile set, falling back to default profiles: default
2018-07-16 10:18:03.659  INFO 4737 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot
[email protected]
7fbdb894: startup date [Mon Jul 16 10:18:03 CST 2018]; root of context hierarchy

如果想要更改的話也簡單,就是在資原始檔的下面新增一個banner.txt檔案,然後將想要的展示的資訊填寫進去就行了,專案啟動的時候回自動去載入這個檔案。

___.                                                  .__
\_ |__  __ _____  _____ __   ______  _  ____ __  _____|  |__  __ __
 | __ \|  |  \  \/  /  |  \_/ __ \ \/ \/ /  |  \/  ___/  |  \|  |  \
 | \_\ \  |  />    <|  |  /\  ___/\     /|  |  /\___ \|   Y  \  |  /
 |___  /____//__/\_ \____/  \___  >\/\_/ |____//____  >___|  /____/
     \/            \/           \/                  \/     \/       
2018-07-16 10:19:53.941  INFO 4745 --- [           main] c.e.F.FirstSpringBootApplication         : Starting FirstSpringBootApplication on hupengfeideMacBook-Pro.local with PID 4745 (/Users/hupengfei/mygit/FirstSpringBoot/out/production/classes started by hupengfei in /Users/hupengfei/mygit/FirstSpringBoot)
2018-07-16 10:19:53.945  INFO 4745 --- [           main] c.e.F.FirstSpringBootApplication         : No active profile set, falling back to default profiles: default
2018-07-16 10:19:54.015  INFO 4745 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]15a04efb: startup date [Mon Jul 16 10:19:54 CST 2018]; root of context hierarchy

此時就會發現啟動的影象變了。將字母生成字元畫

如果不想列印任何的影象資訊,那麼只需要在資原始檔下的配置檔案中設定即可。

spring:
    main:
        banner-mode: "off"

3.定製SpringApplication

如果預設的SpringApplication不符合自己想要的配置結果,那麼可以進行定製化的配置。例如像上一章節的如果像關閉啟動的影象資訊,上一章節是在配置檔案中進行關閉,那麼也可以在啟動的main檔案中進行定製化關閉。

public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
}

對於完整的SpringApplication配置選項,可以參考SpringApplication文件

4.Spring事件的監聽

除了一些正常的Spring的事件監聽,例如ContextRefreshedEvent,有時候也有可能需要一些特殊的事件的監聽。下面就列出一些特殊的事件,例如你想在專案啟動的時候做一些事情,或者是專案啟動失敗的時候做一些事情。這些SpringBoot都提供有相應的功能。

事件名稱 何時被呼叫
ApplicationEnvironmentPreparedEvent 環境準備好,Spring容器被建立之前
ApplicationPreparedEvent 在專案啟動refresh之前
ApplicationReadyEvent 在專案啟動成功之後
ApplicationFailedEvent 在專案啟動時發生異常

可以看到每個事件被觸發時的時間。

I AM ApplicationEnvironmentPreparedEvent

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.7.RELEASE)

2018-07-16 14:44:37.110  INFO 5397 --- [           main] c.e.F.FirstSpringBootApplication         : Starting FirstSpringBootApplication on hupengfeideMacBook-Pro.local with PID 5397 (/Users/hupengfei/mygit/FirstSpringBoot/out/production/classes started by hupengfei in /Users/hupengfei/mygit/FirstSpringBoot)
2018-07-16 14:44:37.114  INFO 5397 --- [           main] c.e.F.FirstSpringBootApplication         : No active profile set, falling back to default profiles: default
I AM ApplicationPreparedEvent
2018-07-16 14:44:37.168  INFO 5397 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]528c868: startup date [Mon Jul 16 14:44:37 CST 2018]; root of context hierarchy
2018-07-16 14:44:38.299  INFO 5397 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-07-16 14:44:38.309  INFO 5397 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-07-16 14:44:38.310  INFO 5397 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2018-07-16 14:44:38.391  INFO 5397 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-07-16 14:44:38.391  INFO 5397 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1227 ms
2018-07-16 14:44:38.530  INFO 5397 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-07-16 14:44:38.539  INFO 5397 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-07-16 14:44:38.540  INFO 5397 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-07-16 14:44:38.540  INFO 5397 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-07-16 14:44:38.540  INFO 5397 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-07-16 14:44:38.851  INFO 5397 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]528c868: startup date [Mon Jul 16 14:44:37 CST 2018]; root of context hierarchy
2018-07-16 14:44:38.929  INFO 5397 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.example.FirstSpringBoot.FirstSpringBootApplication.home()
2018-07-16 14:44:38.933  INFO 5397 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-07-16 14:44:38.933  INFO 5397 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-07-16 14:44:38.960  INFO 5397 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-16 14:44:38.960  INFO 5397 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-16 14:44:38.995  INFO 5397 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-07-16 14:44:39.197  INFO 5397 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-16 14:44:39.272  INFO 5397 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
I AM ApplicationReadyEvent

程式碼如下,這是使用了內部類的寫法,也可以自己建一個類實現ApplicationListener然後傳入所建的類即可。

public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FirstSpringBootApplication.class);
        app.addListeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> {
            System.out.println("I AM ApplicationEnvironmentPreparedEvent");
        });
        app.addListeners((ApplicationListener<ApplicationPreparedEvent>) event -> {
            System.out.println("I AM ApplicationPreparedEvent");
        });
        app.addListeners((ApplicationListener<ApplicationReadyEvent>) event -> {
            System.out.println("I AM ApplicationReadyEvent");
        });
        app.run(args);
    }

5.ApplicationRunner和CommandLineRunner

有時候在業務中會碰到這些需求,要求在容器啟動的時候執行一些內容,例如讀取配置檔案,資料庫的連線等等。SpringBoot提供了兩個介面為我們解決這些問題。一個是ApplicationRunner另一個是CommandLineRunner

5.1 CommandLineRunner介面

@Component
public class AppliRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("--------CommandLineRunner---------"+Arrays.asList(args));
    }
}

然後在設定裡面設定Program arguments

<center><img src="http://p9jfgo4wc.bkt.clouddn.com/option.jpeg"/></center>

然後專案啟動就可以發現輸出了這些資訊

2018-07-16 16:56:08.216  INFO 5745 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-16 16:56:08.278  INFO 5745 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
--------CommandLineRunner---------[aaa,bbbb]
2018-07-16 16:56:08.282  INFO 5745 --- [           main] c.e.F.FirstSpringBootApplication         : Started FirstSpringBootApplication in 2.557 seconds (JVM running for 3.227)
Disconnected from the target VM, address: '127.0.0.1:59214', transport: 'socket'

5.2 ApplicationRunner介面

ApplicationRunner介面和CommandLineRunner介面的不同之處在於引數的不同,ApplicationRunner介面的傳參是ApplicationArguments,是對引數的一層封裝。而CommandLineRunner介面的引數是可變的String。

@Component
public class AppliRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("-----ApplicationRunner----"+args.getOptionNames());
        System.out.println("-----ApplicationRunner----name:"+args.getOptionValues("name"));
        System.out.println("-----ApplicationRunner----age:"+args.getOptionValues("age"));
    }
}

在啟動設定中設定參引數如下

<center><img src="http://p9jfgo4wc.bkt.clouddn.com/option2.jpeg"/></center> 然後在啟動的時候可以發現如下的引數

2018-07-16 17:15:16.502  INFO 5825 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-07-16 17:15:16.564  INFO 5825 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-----ApplicationRunner----[name, age]
-----ApplicationRunner----name:[不學無數]
-----ApplicationRunner----age:[23]
2018-07-16 17:15:16.568  INFO 5825 --- [           main] c.e.F.FirstSpringBootApplication