一、导航
本节内容简介:
1. 开发之前环境检查
2. 创建pom.xml并导入依赖
3. 编写代码
4. 代码解释
5. 运行代码
6. 创建可执行的jar
二、开发之前环境检查
让我们在Java中开发一个简单的 Hello World 的Web应用程序,来介绍Spring Boot一些主要的功能。
这里将使用Maven构建该项目。
在开始之前,打开终端(windwos cmd)来验证java版本和maven版本
C:\Users\SEELE>java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
这里要注意检查maven版本不是maven -v,而是mvn -v
C:\Users\SEELE>mvn -v
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1...
三、创建pom.xml并导入依赖
- 使用idea创建一个maven项目,并添加maven 父类依赖
<?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.likeoak</groupId>
<artifactId>springboot</artifactId>
<version>1.0.0</version>
<!--添加父类依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
</project>
- 添加web依赖
<!--web依赖-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
四、编写代码
默认情况下,Maven将从src/main/java编译源代码,因此您需要创建该文件夹结构,然后添加一个名为src/main/java/Example.java的文件:
注意:官方建议不要使用默认的default包来创建启动类,这样会导致所有的包都会被扫描,包括jar
package com.likeoak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* The type Spring boot example.
*/
RestController
EnableAutoConfiguration
public class SpringBootExample {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootExample.class, args);
}
}
五、代码解释
尽管以上代码不多,但是却发生很多事情,让我们一步一步来解释吧
1. 注解解释
上面一共用了三个注解 @RestController ,@RequestMapping, @EnableAutoConfiguration
@RestController是一个被称为构造性(stereotype)的注解,它表示的意思是是一个REST风格的Controller
@RequestMapping 这个注解是提供路由信息,所有HTTP的 "/"这个请求都会被这个home方法捕获,这个和@RestController一起的意思是,当访问"/"这个路径的时候,就以字符串的形式返回"Hello World!"
@EnableAutoConfiguration 这个注解的意思是告诉spring boot 根据你配置的jar来猜测你想如何配置spring
这里我们配置了spring-boot-starter-web这个jar,spring boot 就会为我们自动配置tomcat和SprngMVC的相关配置
,可以参考下面spring-boot-starter-web依赖包,看到里面有springMVC和tomcat的引用
附spring-boot-starter-web依赖包
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<artifactId>spring-boot-starter-web</artifactId>
<name>Spring Boot Web Starter</name>
<description>Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container</description>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
附spring-boot-starter-tomcat依赖
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<artifactId>spring-boot-starter-tomcat</artifactId>
<name>Spring Boot Tomcat Starter</name>
<description>Starter for using Tomcat as the embedded servlet container. Default
servlet container starter used by spring-boot-starter-web</description>
<url>http://projects.spring.io/spring-boot/</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>http://www.spring.io</url>
</organization>
<properties>
<main.basedir>${basedir}/../..</main.basedir>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
</dependency>
</dependencies>
</project>
2. main方法
main方法是一个java标准入口方法。这里main方法通过调用runm,将业务委托给了 Spring Boot的 SpringApplication 类。SpringApplication将引导我们启动spring,相应的启动被自动配置的tomcat web服务器,这里我们需要将主类 SpringBootExample作为参数传给run方法,告诉spring boot 那个是主类,并传递args参数给 spring boot,对于这个args参数,我们后续会讲解.
六、运行代码
直接运行main方法
运行结果:
.__ .__ __ __
__ _ ____ _ ____ _ __ | | |__| | __ ____ _________ | | __ ____ ____ _____
\ \/ \/ /\ \/ \/ /\ \/ \/ / | | | | |/ // __ \/ _ \__ \ | |/ / _/ ___\/ _ \ / \
\ / \ / \ / | |_| | <\ ___( <_> ) __ \| < \ \__( <_> ) Y Y \
\/\_/ \/\_/ \/\_/ /\ |____/__|__|_ \\___ >____(____ /__|_ \ /\ \___ >____/|__|_| /
\/ \/ \/ \/ \/ \/ \/ \/
2017-06-25 18:58:59.061 INFO 10640 --- [ main] com.likeoak.SpringBootExample : Starting SpringBootExample on SEELE-PC with PID 10640 (G:\Mybook\springBoot\target\classes started by SEELE in G:\Mybook\springBoot)
2017-06-25 18:58:59.065 INFO 10640 --- [ main] com.likeoak.SpringBootExample : No active profile set, falling back to default profiles: default
2017-06-25 18:58:59.107 INFO 10640 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b8ca3c8: startup date [Sun Jun 25 18:58:59 CST 2017]; root of context hierarchy
2017-06-25 18:59:00.581 INFO 10640 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-25 18:59:00.597 INFO 10640 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-06-25 18:59:00.598 INFO 10640 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-06-25 18:59:00.748 INFO 10640 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-06-25 18:59:00.748 INFO 10640 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1645 ms
2017-06-25 18:59:00.900 INFO 10640 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-25 18:59:00.904 INFO 10640 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-25 18:59:00.905 INFO 10640 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-25 18:59:00.905 INFO 10640 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-25 18:59:00.906 INFO 10640 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-25 18:59:01.247 INFO 10640 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b8ca3c8: startup date [Sun Jun 25 18:58:59 CST 2017]; root of context hierarchy
2017-06-25 18:59:01.337 INFO 10640 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.likeoak.SpringBootExample.home()
2017-06-25 18:59:01.342 INFO 10640 --- [ 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)
2017-06-25 18:59:01.342 INFO 10640 --- [ 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)
2017-06-25 18:59:01.376 INFO 10640 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-25 18:59:01.376 INFO 10640 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-25 18:59:01.452 INFO 10640 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-25 18:59:01.669 INFO 10640 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-06-25 18:59:01.760 INFO 10640 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-25 18:59:01.764 INFO 10640 --- [ main] com.likeoak.SpringBootExample : Started SpringBootExample in 3.182 seconds (JVM running for 3.816)
然后访问 http://localhost:8080/
结果:
Hello World!
七、 创建可执行的jar
这里通过maven插件来实现,在pom.xml中引入spring-boot-maven-plugin
<!-- 可执行jar-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
执行mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building springboot 1.0.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ springboot ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ springboot ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ springboot ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory G:\Mybook\springBoot\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ springboot ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ springboot ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ springboot ---
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.2.RELEASE:repackage (default) @ springboot ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.790 s
[INFO] Finished at: 2017-06-25T19:47:08+08:00
[INFO] Final Memory: 19M/226M
[INFO] ------------------------------------------------------------------------
打包之后,再target下面会出现spring-1.0.0.jar包
运行:
java -jar spring-1.0.0.jar
后续会继续推出这一系列spring boot的文章
本人网站:一起学JAVA
网友评论