一个简单的SpringBoot应用
1.环境准备
-jdk1.8:java version "1.8.0_201"-apache-maven-3.6.3及以上
-IntelliJ IDEA 2019.3.4 x64、STS
Spring Boot 2.2.6.RELEASE
注意:Spring Boot 2.2.6.RELEASE requires Java 8 and is compatible up to Java 13 (included). Spring Framework 5.2.5.RELEASE or above is also required.
2.SpringBoot-helloworld项目
功能:游览器发送hello请求,服务器接收请求,响应Hello World字符串- 创建一个Maven工程
- 导入SpringBoot相关的依赖
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
<!-- Override inherited settings -->
<description/>
<developers>
<developer/>
</developers>
<licenses>
<license/>
</licenses>
<scm>
<url/>
</scm>
<url/>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 编写一个主程序:启动SpringBoot项目
(1) @SpringBootApplication:标识一个主程序,说明这是一个SpringBoot应用
(2) run()方法启动Spring
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloMainApplication {
public static void main(String[] args) {
SpringApplication.run(HelloMainApplication.class,args);
}
}
- 编写相关的Controller类
@ResponseBody:把 Hello World! 的内容写给游览器
package com.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!";
}
}
- 运行主程序测试
- 我们可以看到tomcat已经启动了,且端口是8080,我们通过游览器验证一下,输入 localhost:8080/hello,可以看到运行成功且显示了 Hello World!字符串。
- 简化部署
将应用打包成Jar包,直接使用命令行Java -jar SpringBoot-helloworld-1.0-SNAPSHOT.jar,简化部署后,我们可以直接应用,无需配置其他的环境变量,变得很简便。
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
同时这个例子在官网上也可以查看:https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/html/getting-started.html#