1.参考文档
https://spring.io/guides/gs/spring-boot/
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
spring boot是非常简单的,已经集成了非常多的东西,只需要写少许代码就能实现一个web服务。本例,两个java文件,一个pom文件,既可。
2.在idea新建一个maven项目。
3.修改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>org.springframework</groupId>
<artifactId>gs-spring-boot</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.在src/main/java下新建package hello
5.在hello下新建文件HelloController.java,内容如下
package hello;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
6.在hello下新建文件Application.java,内容如下
package hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//下面的函数不是必需,可以注释掉
// @Bean
// public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
// return args -> {
//
// System.out.println("Let's inspect the beans provided by Spring Boot:");
//
// String[] beanNames = ctx.getBeanDefinitionNames();
// Arrays.sort(beanNames);
// for (String beanName : beanNames) {
// System.out.println(beanName);
// }
//
// };
// }
}
7.在pom.xml文件所在的目录执行mvn pakcage,编译打包
8.在pom.xml文件所在目录执行 java -jar target/gs-spring-boot-0.1.0.jar
9.在浏览器输入localhost:8080,可以看到字符串Greetings from Spring Boot!
7.在pom.xml文件所在的目录执行mvn pakcage,编译打包
8.在pom.xml文件所在目录执行 java -jar target/gs-spring-boot-0.1.0.jar
9.在浏览器输入localhost:8080,可以看到字符串Greetings from Spring Boot!