Spring Boot 学习笔记

学习代码第一步:如何写 Hello world ?

1、新建项目

新建一个 Maven Java 工程,在 pom.xml 文件中添加 Spring Boot Maven 依赖:

复制代码
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.6</version>
</parent>
复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin </artifactId>
        </plugin>
    </plugins>
</build>

2、创建启动类

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

3、创建HelloController

java 复制代码
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String hello(){
        return "Hello world!!";
    }
}

4、启动

运行App的Main函数,之后打开浏览器输入地址:http://127.0.0.1:8080/ 就可以看到 Hello world!了。

5、返回JSON数据

5.1、编写一个实体类Demo

java 复制代码
package org.example.bean;

public class Demo {
    private long id ;
    private  String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}

5.2、编写 DemoController

在 DemoController 加上@RestController 和@RequestMapping 注解;

java 复制代码
package org.example.web;

import org.example.bean.Demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController()
@RequestMapping("/demo")
public class DemoController {

    @RequestMapping("/getDemo")
    public Demo getDemo(){
        Demo demo = new Demo();
        demo.setId(1L);
        demo.setName("风萧萧1999");
        return demo;
    }

}

5.3、测试

那么在浏览器访问地址:http://127.0.0.1:8080/demo/getDemo 返回如下数据:

相关推荐
用户9083246027320 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
齐生121 小时前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29171 天前
D006 【模板】并查集
笔记
用户8307196840822 天前
Spring Boot 集成 RabbitMQ :8 个最佳实践,杜绝消息丢失与队列阻塞
spring boot·后端·rabbitmq
Java水解2 天前
Spring Boot 视图层与模板引擎
spring boot·后端
Java水解2 天前
一文搞懂 Spring Boot 默认数据库连接池 HikariCP
spring boot·后端
洋洋技术笔记2 天前
Spring Boot Web MVC配置详解
spring boot·后端
tingshuo29172 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
初次攀爬者3 天前
Kafka 基础介绍
spring boot·kafka·消息队列
用户8307196840823 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp