一. 环境准备
重要,若环境与以下不同可能会出现误差报错
- jdk:1.8
- maven: 3.3(3.3以上皆可,不推荐使用3.6以上)
- IDEA:2019(2017以上皆可)
- springboot:1.5.9(不推荐2.x.x版本,不稳定)
二. 步骤
-
new一个maven 的普通java工程,目录结构如下:
-
在pom文件中导入springboot的相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<grouopId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 编写一个主程序:启动springboot应用
HelloWorldMainApplication.java
package com.atguigu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
@SpringBootApplication 来标注这是一个主程序类,说明这是一个springboot应用
*/
@SpringBootApplication
public class HelloWorldMainApplication {
public static void main(String[] args) {
//Spring应用启动起来
SpringApplication.run(HelloWorldMainApplication.class, args);
}
}
- 编写相关的controller、Service
HelloController.java
package com.atguigu.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
}
- 启动程序
- 使用浏览器访问localhost:8080/hello
三. 简化部署
由上面步骤可知在springboot中无需配置tomcat即可进行访问。下面使用maven插件打包,使用java -jar
命令来运行程序
- 在pom文件中添加以下:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
点击:
-
复制以下jar到桌面
-
在cmd中进入桌面路径,输入
java -jar spring-boot01helloworld-1.0-SNAPSHOT.jar
即可。使用浏览器访问localhost:8080/hello