Java 系统学习 | Springboot 写 hello world

发布时间 2023-12-28 13:58:49作者: 菜乌

经过一段时间基础学习,现在开始使用 Springboot 框架完成项目,特地记录一下,方便后续查漏补缺。

本篇使用 Springboot3 框架,IDEA2022 编辑器,java17 版本。

新建项目

  • file -> new -> project
    image

  • 弹框中填入自己的信息

    • Name 项目名称

    • Location 项目存放路径

    • Language Java

    • Build system Maven

    • JDK 选择自己安装的版本

    image

  • 新建后的目录结构如下
    image


pom.xml 配置

  • parent
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>3.1.3</version>
</parent>
  • 引入 spring-boot-web 依赖包
<dependencies>
	<!-- web开发的场景启动器 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>
  • 刷新 maven,下载导入依赖

    编辑器右上角【Maven】,点击 reload,直到代码中红色全部消失


生成项目启动入口

  • application 生成

    image

  • 创建入口 main 方法,加上注解 @SpringBootApplication

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
  • 启动内置 tomcat,下面 Console 中看到启动信息

    image


使用测试类进行测试

  • 新建 package controller,创建 HelloController 类

    image

  • 类文件中创建 hello 方法进行测试

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {

        return "hello,world!";
    }
}
  • 浏览器访问 http://localhost:8080/hello

    image



hello,world 结束后,开始完成一个小项目!