Spring boot- Spring快速开始

Posted mengrennwpu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot- Spring快速开始相关的知识,希望对你有一定的参考价值。

本系列博客将学习并运用Spring Boot, 尽量会涉及到Spring Boot的方方面面,且会参考Spring Boot的官方文档,相关英文书籍,以及相关博客等知识,争取做到详尽易懂。

1. Spring Boot简介

(1) Spring Boot的目的在于构件可以运行的独立或基于生产级别的Spring应用。其特点在于大多数的Spring Boot应用均需要很少的配置,且容易上手。

(2) 可以使用Spring Boot创建Java程序,且基于java -jar命令执行或更传统的war包部署。

(3) Spring Boot也包含命令行工具,可以运行Spring脚本。

(4) Spring Boot的主要目标在于:

a. 提供全部Spring开发的快速、可访问的起步经验

b. 开箱即用,但随着需求的不同,很快被忽略的默认值。

c. 提供普通大项目类的非功能性特征,如嵌入服务,安全,矩阵, 健康检查及外部配置等

d. 绝没有代码生成,也没有XML的配置需求。

2. 系统要求

(1) Spring Boot2.0.0需要Java 8+, 且已嵌入的容器包括: Tomcat 8.5, Jetty 9.4, Undertow 1.3

3. Spring Boot安装

(1) Spring Boot的依赖使用org.springframework.boot.groupId。使用Maven POM文件可继承spring-boot-starter-parent项目,并声明一个或多个"Starter"依赖。

详细信息可参考如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<!-- Add Spring repositories -->
<!-- (you don\'t need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
View Code

 其中, spring-boot-starter-parent是使用spring boot的很好的方法,但并不总是适用,可能有时你需要从另一个parent POM继承。

 (2) 安装Spring Boot CLI

Spring Boot CLI命令行工具可以使你快速原生使用Spring,其允许运行Groovy脚本。可以手工安装,在windows中执行bin/目录下的spring.bat脚本,即可设置运行所需的环境变量。

1) 快速使用spring boot CLI

首先创建groovy脚本,命令为app.groovy。

@RestController
class ThisWillActuallyRun{
  @RequestMapping("/")
  String home(){
    "Hello World!"
  }
}
View Code

 然后在该脚本的所在目录下执行,第一次执行时速度较慢,因为需要加载所需依赖:

spring run app.groovy

  运行的日志如下:

F:\\software\\spring-2.0.0.BUILD-SNAPSHOT\\bin>spring run app.groovy
Resolving dependencies......

  .   ____          _            __ _ _
 /\\\\ / ___\'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\
 \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  \'  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.0.0.BUILD-SNAPSHOT)

2017-12-03 14:38:07.187  INFO 7776 --- [       runner-0] o.s.boot.SpringApplicat
ion               : Starting application on WangSong with PID 7776 (F:\\software\\
spring-2.0.0.BUILD-SNAPSHOT\\lib\\spring-boot-cli-2.0.0.BUILD-SNAPSHOT.jar started
 by Administrator in F:\\software\\spring-2.0.0.BUILD-SNAPSHOT\\bin)
2017-12-03 14:38:07.215  INFO 7776 --- [       runner-0] o.s.boot.SpringApplicat
ion               : No active profile set, falling back to default profiles: def
ault
2017-12-03 14:38:10.862  INFO 7776 --- [       runner-0] ConfigServletWebServerA
pplicationContext : Refreshing org.springframework.boot.web.servlet.context.Anno
tationConfigServletWebServerApplicationContext@71fdc9: startup date [Sun Dec 03
14:38:10 CST 2017]; root of context hierarchy
2017-12-03 14:38:19.287  INFO 7776 --- [       runner-0] o.h.v.i.engine.Validato
rFactoryImpl      : HV000238: Temporal validation tolerance set to 0.
2017-12-03 14:38:29.058  INFO 7776 --- [       runner-0] o.s.b.w.embedded.tomcat
.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2017-12-03 14:38:29.156  INFO 7776 --- [       runner-0] o.apache.catalina.core.
StandardService   : Starting service [Tomcat]
2017-12-03 14:38:29.178  INFO 7776 --- [       runner-0] org.apache.catalina.cor
e.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-12-03 14:38:29.354  INFO 7776 --- [ost-startStop-1] o.a.catalina.core.AprLi
fecycleListener   : The APR based Apache Tomcat Native library which allows opti
mal performance in production environments was not found on the java.library.pat
h: [D:\\Program Files\\Java\\jdk1.8.0_66\\bin;C:\\Windows\\Sun\\Java\\bin;C:\\Windows\\sys
tem32;C:\\Windows;C:\\ProgramData\\Oracle\\Java\\javapath;D:\\Program Files\\apache-ant
\\bin;D:\\Program Files\\Java\\jdk1.8.0_66\\bin;D:\\Program Files\\Java\\jdk1.8.0_66\\jre
\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32
\\WindowsPowerShell\\v1.0\\;C:\\Program Files\\Common Files\\Thunder Network\\KanKan\\Co
decs;D:\\MATLAB\\bin\\win32;D:\\bin\\win32;C:\\Program Files\\Microsoft SQL Server\\100\\
Tools\\Binn\\;C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\;D:\\Program Files
\\win7缇庡寲澶у笀\\Windows7Master;D:\\Program Files\\MATLAB\\R2011a\\runtime\\win32;D:
\\Program Files\\MATLAB\\R2011a\\bin;D:\\Program Files\\OpenCV\\opencv\\build\\x86\\vc10\\b
in;D:\\PProgram Files\\Windows7Master;C:\\Program Files\\Microsoft SQL Server\\90\\Too
ls\\binn\\;C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\;C:\\Program Files\\Mic
rosoft SQL Server\\80\\Tools\\Binn\\;C:\\Program Files\\mysql\\MySQL Server 5.5\\bin;D:\\
Program Files\\MongoDB\\mongodb-win32-i386-2.6.4\\bin;C:\\Windows\\system32;C:\\Window
s;C:\\Windows\\System32\\Wbem;D:\\Program Files\\VisualSVN Server\\bin;D:\\Program File
s\\TortoiseSVN\\bin;F:\\software\\apache-maven-3.3.9\\bin;D:\\Program Files\\Sublime Te
xt 3;D:\\Program Files\\Python\\Python35-32;;D:\\Program Files\\Anaconda3;D:\\Program
Files\\Anaconda3\\Scripts;D:\\Program Files\\Anaconda3\\Library\\bin;D:\\Program Files\\
vc++\\Microsoft Visual Studio\\Common\\MSDev98\\Bin;D:\\Program Files\\vc++\\Microsoft
Visual Studio\\Common\\Tools;D:\\Program Files\\vc++\\Microsoft Visual Studio\\VC98\\bi
n;D:\\ModelsimSE6.5\\Modelsim\\win32;D:\\Program Files\\OpenCV\\opencv\\build\\x86\\vc10\\
bin;C:\\Users\\Administrator\\AppData\\Roaming\\Dashlane\\1.7.7.30648\\bin\\Firefox_Exte
nsion\\{442718d9-475e-452a-b3e1-fb1ee16b8e9f}\\components;.]
2017-12-03 14:38:30.086  INFO 7776 --- [ost-startStop-1] org.apache.catalina.loa
der.WebappLoader  : Unknown loader org.springframework.boot.cli.compiler.Extende
dGroovyClassLoader$DefaultScopeParentClassLoader@17a66d8 class org.springframewo
rk.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader
2017-12-03 14:38:30.270  INFO 7776 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[loc
alhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-12-03 14:38:30.272  INFO 7776 --- [ost-startStop-1] o.s.web.context.Context
Loader            : Root WebApplicationContext: initialization completed in 1941
0 ms
2017-12-03 14:38:30.940  INFO 7776 --- [ost-startStop-1] o.s.b.w.servlet.Servlet
RegistrationBean  : Mapping servlet: \'dispatcherServlet\' to [/]
2017-12-03 14:38:30.999  INFO 7776 --- [ost-startStop-1] o.s.b.w.servlet.FilterR
egistrationBean   : Mapping filter: \'characterEncodingFilter\' to: [/*]
2017-12-03 14:38:31.003  INFO 7776 --- [ost-startStop-1] o.s.b.w.servlet.FilterR
egistrationBean   : Mapping filter: \'hiddenHttpMethodFilter\' to: [/*]
2017-12-03 14:38:31.005  INFO 7776 --- [ost-startStop-1] o.s.b.w.servlet.FilterR
egistrationBean   : Mapping filter: \'httpPutFormContentFilter\' to: [/*]
2017-12-03 14:38:31.007  INFO 7776 --- [ost-startStop-1] o.s.b.w.servlet.FilterR
egistrationBean   : Mapping filter: \'requestContextFilter\' to: [/*]
2017-12-03 14:38:32.056  INFO 7776 --- [       runner-0] o.h.v.i.engine.Validato
rFactoryImpl      : HV000238: Temporal validation tolerance set to 0.
2017-12-03 14:38:32.873  INFO 7776 --- [       runner-0] s.w.s.m.m.a.RequestMapp
ingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.
servlet.context.AnnotationConfigServletWebServerApplicationContext@71fdc9: start
up date [Sun Dec 03 14:38:10 CST 2017]; root of context hierarchy
2017-12-03 14:38:33.320  INFO 7776 --- [       runner-0] s.w.s.m.m.a.RequestMapp
ingHandlerMapping : Mapped "{[/]}" onto public java.lang.String ThisWillActually
Run.home()
2017-12-03 14:38:33.336  INFO 7776 --- [       runner-0] s.w.s.m.m.a.RequestMapp
ingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.Res
ponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframewo
rk.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet
.http.HttpServletRequest)
2017-12-03 14:38:33.340  INFO 7776 --- [       runner-0] s.w.s.m.m.a.RequestMapp
ingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.spr
ingframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web
.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequ
est,javax.servlet.http.HttpServletResponse)
2017-12-03 14:38:33.500  INFO 7776 --- [       runner-0] o.s.w.s.handler.SimpleU
rlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class or
g.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-03 14:38:33.501  INFO 7776 --- [       runner-0] o.s.w.s.handler.SimpleU
rlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.spring
framework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-03 14:38:33.662  INFO 7776 --- [       runner-0] o.s.w.s.handler.SimpleU
rlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [clas
s org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-12-03 14:38:35.337  INFO 7776 --- [       runner-0] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2017-12-03 14:38:35.844  INFO 7776 --- [       runner-0] o.s.b.w.embedded.tomcat
.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path \'\'
2017-12-03 14:38:35.860  INFO 7776 --- [       runner-0] o.s.boot.SpringApplicat
ion               : Started application in 37.269 seconds (JVM running for 63.37
5)
2017-12-03 14:38:37.391  INFO 7776 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[loc
alhost].[/]       : Initializing Spring FrameworkServlet \'dispatcherServlet\'
2017-12-03 14:38:37.393  INFO 7776 --- [nio-8080-exec-2] o.s.web.servlet.Dispatc
herServlet        : FrameworkServlet \'dispatcherServlet\': initialization started

2017-12-03 14:38:37.561  INFO 7776 --- [nio-8080-exec-2] o.s.web.servlet.Dispatc
herServlet        : FrameworkServlet \'dispatcherServlet\': initialization complet
ed in 167 ms
View Code

 最后通过浏览器访问localhost:8080,结果如下图:

4. 开发第一个Spring Boot应用

(1) 创建Maven POM

创建的POM文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>
<!-- Additional lines to be added here... -->
<!-- (you don\'t need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
View Code 

(2) 增加classpath依赖

spring boot有很多启动器依赖,本例web服务采用spring-boot-starter-web依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies
View Code 

(3) 写代码

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class HelloWorld {

    @RequestMapping("/")
    @ResponseBody
    String home(){
        return "Hello World";
    }
    
    public static void main(String[] args) {
        SpringApplication.run(HelloWorld.class, args);
    }
    
}
View Code 

其中:

@RestController注解为stereotype注解,其为人们阅读代码提供一些提示,对于Spring来说,该类具有特定作用。上述例子为web@Controller,所以Spring在处理传入的web请求时会考虑该类。

@RequestMapping注解提供路由信息,其告诉Spring,任何具有"/"的HTTP请求都映射到home方法。@RestController注解告诉Spring将生成的字符串直接返回给请求者。

@EnableAutoConfiguration注解告诉spring boot根据添加的依赖关系来猜测你将如何配置Spring。在该例中,由于spring-boot-starter-web添加了Tomcat和Spring MVC,自动配置将假定你正在开发Web应用,并相应地配置Spring。

main方法中调用SpringApplication.run方法,启动Spring, 然后启动自动配置的Tomcat web服务。我们需要将HelloWorld.class作为一个参数传递给run方法,告知SpringApplication,它是主要的Spring组件。

(4) 运行之后,返回localhost:8080地址即可得到"Hello World"的显示。

(5) 创建可执行的jar包

在POM文件中增加如下插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
View Code 

然后执行打包命令,即可生成可执行的jar包,进一步运行部署。

以上是关于Spring boot- Spring快速开始的主要内容,如果未能解决你的问题,请参考以下文章

spring-boot第一章:快速开始

Spring Boot 最佳实践快速入门

Spring Boot 1-项目快速搭建

使用向导快速创建spring boot应用

Spring Boot Admin 参考指南

Spring Boot快速入门:http请求