不學無數——SpringBoot入門Ⅱ

SpringBoot

1.Starters

Starters是一套技術,是什麼技術呢?是SpringBoot整理出來,人們常常要用的技術。有了starters人們在想要使用這些技術的時候,就不用扒以前的老代碼將那些依賴啊或者配置的都拷貝過來,只須要加上SpringBoot提供的依賴就行,它自動會進行依賴管理。例如,若是你想在SpringBoot項目中集成JPA,那麼只須要在引入jar包的地方加上spring-boot-starter-data-jpa便可,SpringBoot會自動將其和其餘所依賴的包加載進項目中。html

全部SpringBoot提供的Starters命名都有一套規則,spring-boot-starter-*,其中的*就是你想要引用的技術的名稱。java

下面列一些Startersgit

名稱 描述
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官方文檔web

2.自定義啓動頁面

在項目啓動的時候,在打印日誌的上面會有一個圖像,這個就是啓動的時候自動加載的。就像下面這樣初始圖像是這樣的。spring

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: 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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@15a04efb: startup date [Mon Jul 16 10:19:54 CST 2018]; root of context hierarchy

複製代碼

此時就會發現啓動的圖像變了。將字母生成字符畫apache

若是不想打印任何的圖像信息,那麼只須要在資源文件下的配置文件中設置便可。編程

spring:
    main:
        banner-mode: "off"
複製代碼

3.定製SpringApplication

若是默認的SpringApplication不符合本身想要的配置結果,那麼能夠進行定製化的配置。例如像上一章節的若是像關閉啓動的圖像信息,上一章節是在配置文件中進行關閉,那麼也能夠在啓動的main文件中進行定製化關閉。api

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

對於完整的SpringApplication配置選項,能夠參考SpringApplication文檔tomcat

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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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

而後項目啓動就能夠發現輸出了這些信息

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"));
    }
}
複製代碼

在啓動設置中設置參參數以下

而後在啓動的時候能夠發現以下的參數
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 

複製代碼
相關文章
相關標籤/搜索