1. 创建一个 springboot 项目

使用 idea 创建的基本步骤:

idea编写第一个springboot程序_maven

 

 idea编写第一个springboot程序_xml_02

idea编写第一个springboot程序_xml_03

idea编写第一个springboot程序_maven_04

2. 加入父级,起步依赖

pom.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http:///POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:///POM/4.0.0 http:///xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>

<properties>
<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>

父级依赖(继承 springboot 父级项目的依赖):

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

起步依赖(springboot 开发web项目的起步依赖,由于添加了父级依赖,起步依赖的版本号与父级版本号一致):

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

springboot 提供的项目编译打包插件:

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

3. 创建 springboot 的入口 main 方法

创建后的目录结构

idea编写第一个springboot程序_spring_05

  • 程序入口Application.java须在包的根目录下,也就是 com.example 下,不能在 demo 或 web 下

程序入口是固定写法,启动此程序,启动spring容器,启动内嵌的tomcat:

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);
}

}

4. 创建 Controller

与 springMVC 类似,添加注解访问即可(demo文件夹下面)

@RestController
public class SimpleController {

@RequestMapping("/index")
public String simple1() {
return "你好";
}

}

5. 运行 springboot 的 main 方法

运行 main 方法(启动标识):

idea编写第一个springboot程序_xml_06

访问成功:

idea编写第一个springboot程序_maven_07

 

 

中间报错解决
解决IDEA Initialization error 'https://start.spring.io'