这是基于《Spring中文文档》的操作
这里使用的环境配置:
为了不产生各种工具出现的差别,这里不使用IDE工具,但是实际上可以直接使用Spring suite更方便:
使用http://start.spring.io/ 完成基本文件结构和pom.xml配置:
这里只添加了web依赖:
下载完成后解压,文件结构如下:
查看这里的pom.xml文件:
<?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>zr.test</groupId>
<artifactId>firstdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>firstdemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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>
可以看到,自动添加了相关的支持,spring-boot-maven-plugin用于创建可执行的jar。
可以使用mvn dependency:tree命令用树形来打印项目依赖。
编写java代码
package zr.test.firstdemo;
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;
//告诉Spring用字符串的形式渲染效果,并且直接返回调用者
@RestController
/**
* Spring根据添加的jar依赖猜测你如何配置Spring
* spring-boot-starter-web里面包含了Tomcat和SpringMvc,所以auto-configuration假定你正在开发一个
* web应用
*/
@EnableAutoConfiguration
public class FirstdemoApplication {
@RequestMapping("/example")
String home() {
return "Example Test~~~~";
}
public static void main(String[] args) {
//FirstdemoApplication.class传给run方法告诉SpringBoot谁是主要的Spring组件
SpringApplication.run(FirstdemoApplication.class, args);
}
}
运行代码:
mvn spring-boot:run
打开完成后,使用路径 http://localhost:8080/example 可以查看显示-》“Example Test~~~~”
创建可以执行的jar
这里已经添加了spring-boot-maven-plugin依赖,直接使用mvn package 命令在target目录下生成,这里因为有jdk版本的问题,跳过测试使用 mvn clean package -Dmaven.test.skip=true
完成之后,可以看到target目录下生成了firstdemo-0.0.1-SNAPSHOT.jar.original和firstdemo-0.0.1-SNAPSHOT.jar文件。
使用 jar tvf target/firstdemo-0.0.1-SNAPSHOT.jar可以查看内部的结构。
运行生成的jar包:
使用 java -jar target/firstdemo-0.0.1-SNAPSHOT.jar 可以执行,和之前运行结果相同。