1、新建project时选择Spring Initializr:
2、输入相关信息
3、根据需要选择相关的依赖,这里我只选择web
4、点击finish即可
5、项目建成之后的目录结构。
static:用于存放静态文件
templates:用于存放模板文件,暂不支持jsp。
application.properties:可以在里面进行设置springboot的相关设置
看一下Myspringboot2Application.java
package com.gong.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Myspringboot2Application {
public static void main(String[] args) {
SpringApplication.run(Myspringboot2Application.class, args);
}
}
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 https://maven.apache.org/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.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gong</groupId>
<artifactId>myspringboot2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myspringboot2</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
跟我们之前建的maven项目差别不大,额外多了个springboot的单元测试依赖。
同样的,我们在com.gong.springboot下新建controller包,并在该包下新建HelloWorldController.java
package com.gong.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@ResponseBody
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public String hello(){
return "hello world!";
}
}
启动主配置类:
成功的新建了一个springboot项目。
说明:在类上面标识@ResponseBody,springboot会将这个类的所有方法的数据直接写给浏览器,如果是对象,则将对象转换成json数据。当然,我们也可以将ResponseBody和Controller用一个注解代替:@RestController 。效果是一样的。