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.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
此时就会发现启动的图像变了。将字母生成字符画
如果不想打印任何的图像信息,那么只需要在资源文件下的配置文件中设置即可。
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.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