七叶笔记 » golang编程 » 快速揭开SpringBoot面纱——熵增小讲堂

快速揭开SpringBoot面纱——熵增小讲堂

快速揭开SpringBoot面纱

本文将按照Spring Boot官方文档“II. Getting Started”,从实例的角度,一步步地搭建出一个 Spring Boot 应用,让你能快速的入门 Spring Boot 2.x。

介绍Spring Boot


SpringBoot 官方文档介绍如下:

  • 为所有Spring开发提供一个从根本上更快,且随处可得的入门体验。
  • 开箱即用,但通过不采用默认设置可以快速摆脱这种方式。
  • 提供一系列大型项目常用的非功能性特征,比如:内嵌服务器,安全,指标,健康检测,外部化配置。
  • 绝对没有代码生成,也不需要XML配置。

熵增学院总结如下:

随着新技术的发展, 脚本语言 大行其道的时代(Node JS,Golang,Python,Scala等),Java EE使用Spring逐渐变得笨重起来,大量的XML文件存在与项目中,繁琐的配置,整合第三方框架的配置问题,低下的开发效率和部署效率等等问题。

这些问题在不断的社区反馈下,Spring团队也开发出了相应的框架:Spring Boot。Spring Boot可以说是至少近5年来Spring乃至整个Java社区最有影响力的项目之一,也被人看作是:Java EE开发的颠覆者

Spring Boot解决的问题

(1) Spring Boot使编码变简单

(2) Spring Boot使配置变简单

(3) Spring Boot使部署变简单

(4) Spring Boot使监控变简单

Spring Boot为我们带来了脚本语言开发的效率,但是Spring Boot并没有让我们意外的新技术,都是Java EE开发者常见的技术。

环境要求


  • JAVA 8 及 以上
  • Maven 3.2 及 以上
  • servlet 3.1 及以上

快速初始化


使用Spring Initializr 初始化

  1. 访问 网站
  2. 输入group 和 artifact,以及所需要的依赖
  3. 生成project 并下载使用
  4. 将下载的maven项目导入到IDE中(eclipse, idea, netbeans)

使用Intellj Idea 进行初始化

  1. new module , 选择 Spring Initializr
  2. 输入group 和 artifact,点击 next
  3. 勾选需要的依赖,然后next
  4. 生成spring boot项目

快速编写代码


pom 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
xsi:schemaLocation=" ">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId> demo </artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5. RELEASE </version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
 

JAVA代码

代码路径:src/main/java/Example.java

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web. bin d.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
 

运行Spring Boot


在IDE中运行

如果你是使用intellj idea或者eclipse, 可以直接右键 run as application即可

使用maven运营

在当前目录执行 mvn spring-boot:run

输出如下

 . ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot :: (v2.0.5.RELEASE)
2018-10-05 15:03:03.236 INFO 9316 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication on DESKTOP-8IEBQSU with PID 9316 (F:\demo\target\classes started by anders in E:\codespace\idea\smartblog)
2018-10-05 15:03:03.239 INFO 9316 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2018-10-05 15:03:03.298 INFO 9316 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5d47c63f: startup date [Fri Oct 05 15:03:03 CST 2018]; root of context hierarchy
2018-10-05 15:03:05.354 INFO 9316 --- [ main] o.s.b.w.embedded. Tomcat .TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-10-05 15:03:05.402 INFO 9316 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-10-05 15:03:05.403 INFO 9316 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2018-10-05 15:03:05.424 INFO 9316 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\programsoft\java8\bin;C:\ WINDOWS \Sun\Java\bin;C:\WINDOWS\ System32 ;C:\WINDOWS;D:\install-file\oracle\server\bin;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;D:\programsoft\ git \Git\cmd;D:\programsoft\git\Git\mingw64\bin;D:\programsoft\git\Git\usr\bin;C:\Program Files\MySQL\MySQL Utilities 1.6\;D:\programsoft\tortoisesvn\bin;C:\Program Files\nodejs\;C:\WINDOWS\System32\OpenSSH\;D:\developRepository\nodeModule;C:\Users\anders\AppData\Local\Microsoft\WindowsApps;C:\Users\anders\AppData\Roaming\npm;;D:\programsoft\Microsoft VS Code\bin;.]
2018-10-05 15:03:05.686 INFO 9316 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-05 15:03:05.686 INFO 9316 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2391 ms
2018-10-05 15:03:05.739 INFO 9316 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-10-05 15:03:05.742 INFO 9316 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-05 15:03:05.742 INFO 9316 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-05 15:03:05.742 INFO 9316 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-05 15:03:05.742 INFO 9316 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-05 15:03:05.838 INFO 9316 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-05 15:03:06.002 INFO 9316 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5d47c63f: startup date [Fri Oct 05 15:03:03 CST 2018]; root of context hierarchy
2018-10-05 15:03:06.075 INFO 9316 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.example.demo.DemoApplication.home()
2018-10-05 15:03:06.078 INFO 9316 --- [ 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.servlet.error.BasicErrorController.error( javax .servlet.http.HttpServletRequest)
2018-10-05 15:03:06.079 INFO 9316 --- [ 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.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-10-05 15:03:06.102 INFO 9316 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-05 15:03:06.102 INFO 9316 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-05 15:03:06.237 INFO 9316 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-05 15:03:06.405 INFO 9316 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-10-05 15:03:06.408 INFO 9316 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 3.479 seconds (JVM running for 3.968)
2018-10-05 15:03:09.561 INFO 9316 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-10-05 15:03:09.561 INFO 9316 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-10-05 15:03:09.587 INFO 9316 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 26 ms
 

可执行的jar文件


传统的方式,运行SSM项目必须将项目打成war包,然后将war包放到servlet容器(tomcat, jetty, weblogic等)中才能执行。

而Spring Boot采取了一个不同的方式,直接将所有的依赖,包括servlet依赖都打到了一个jar文件中,然后可以直接运行 java -jar 命令来执行

打成jar包

在项目pom.xml文件目录,执行 mvn package 命令来进行打包

$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.0.5.RELEASE:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
 

如果查看target目录,你应该可以看到myproject-0.0.1-SNAPSHOT.jar,该文件大概有10Mb

执行jar文件

在target目录,执行 java -jar命令运行该应用程序:

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
 . ____ _ __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot :: (v2.0.5.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)
 

后记


本节教程只是带着大家初步感受一下SpringBoot项目,它很快,很精简,零配置,大大的简化了Spring项目的配置。而当前这个“脚本语言大行其道”的时代,SpringBoot的到来无疑给我们带来了脚本语言的开发效率。

比如当下较火的nodejs、golang、python等脚本语言,都内置了net/http库,所以这些脚本语言配置极其简单。

比如nodeje 的koa2配置如下:

const Koa = require('koa')
const app = new Koa()
app.use( async ( ctx ) => {
 ctx.body = 'hello koa2'
})
app.listen(3000)
 

再比如python的flask 如下:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
 return 'Hello World!'
if __name__ == '__main__':
 app.run()
 

以上脚本语言不超过几行代码就可以启动一个web应用,

而java并没有内置http库,所以需要servlet容器来实现http库,而springboot的诞生,彻底解决了java 这一痛点,使用java开发也可以像脚本语言那样简单。

未来5年之内,springboot会依旧大火,无论小项目,中型项目、微服务项目都有Springboot的王者角色!

2019年最新java入门到架构,资源整合大礼包私信“学习”即可领取哦~

一线架构师整理全套学习视频和资料,都在这里等你!

相关文章