环境
OS: windows10
jdk 版本:19
idea版本:IntelliJ IDEA 2022.3.2 (Community Edition)
步骤
Idea新建应用,选择Maven构建方式,“add sample code”。
pom.xml文件修改, 注释<!-- 新增 S --> 和 <!-- 新增 E -->之间的内容为新增,如下:
<?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>
<!-- 新增 S -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 新增 E -->
<groupId>org.example</groupId>
<artifactId>SpringBootTest3</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 新增 S -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- 新增 E -->
</project>
修改默认生成的Main.java
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Main.java添加同级别的package ,命名为controller。
controller中添加HelloController.java,内容如下
package org.example.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController{
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
工程右键->Mavan->Reload project。
build当前module。
测试
运行程序,浏览器输入 localhost:8080/hello,预期:界面显示"Hello"。