环境
OS: windows10
jdk 版本:19
idea版本:IntelliJ IDEA 2022.3.2 (Community Edition)
步骤
Idea新建应用,选择Gradle构建方式,“add sample code”。
当前Idea的Gradle版本可能是7.5.1,提示不支持java19,先忽略该警告,继续创建,创建后修改工程下gradle/wrapper目录下的gradle-wrapper.properties,将7.5.1改为7.6即可,如下:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
build.gradle文件修改,第19行添加内容如下所示
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group 'org.example'
version '1.0-SNAPSHOT'
sourceCompatibility = '19'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
// 添加springboot框架
implementation 'org.springframework.boot:spring-boot-starter-web'
}
test {
useJUnitPlatform()
}
修改默认生成的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);
}
}
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";
}
}
build当前module。
测试
运行程序,浏览器输入 localhost:8080/hello,预期:界面显示"Hello"。