Java Spring Boot入门案例

wen java案例 2

本文目录导读:

Java Spring Boot入门案例

  1. 项目结构
  2. pom.xml
  3. 主应用程序类
  4. 实体类
  5. 控制器
  6. 服务层
  7. 配置文件
  8. 测试类
  9. 运行和测试
  10. 关键点说明

我来为您创建一个完整的Spring Boot入门案例,包含基本配置和REST API示例。

项目结构

spring-boot-demo
├── pom.xml
├── src/main/java/com/example/demo/
│   ├── DemoApplication.java
│   ├── controller/
│   │   └── HelloController.java
│   ├── entity/
│   │   └── User.java
│   └── service/
│       └── UserService.java
└── src/main/resources/
    └── application.yml

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>
    <!-- 继承Spring Boot父项目 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>1.0.0</version>
    <name>spring-boot-demo</name>
    <description>Spring Boot入门案例</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <!-- Web Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Lombok 简化代码 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Spring Boot DevTools 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

主应用程序类

DemoApplication.java

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * Spring Boot启动类
 * @SpringBootApplication 是一个组合注解,包含:
 * - @SpringBootConfiguration:配置类
 * - @EnableAutoConfiguration:自动配置
 * - @ComponentScan:组件扫描
 */
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        // 启动Spring Boot应用
        SpringApplication.run(DemoApplication.class, args);
        System.out.println("Spring Boot应用启动成功!");
    }
}

实体类

User.java

package com.example.demo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * 用户实体类
 * 使用Lombok简化getter/setter方法
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

控制器

HelloController.java - 基础控制器

package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * 基础Hello World控制器
 */
@RestController
@RequestMapping("/api")
public class HelloController {
    /**
     * 基础问候方法
     * GET /api/hello
     */
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
    /**
     * 带参数的问候
     * GET /api/hello?name=张三
     */
    @GetMapping("/hello/param")
    public String helloWithParam(@RequestParam(value = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
    /**
     * 路径参数
     * GET /api/hello/张三
     */
    @GetMapping("/hello/{name}")
    public String helloWithPath(@PathVariable String name) {
        return "Hello, " + name + " from path!";
    }
}

UserController.java - 用户管理控制器

package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 获取所有用户
     * GET /api/users
     */
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    /**
     * 根据ID获取用户
     * GET /api/users/{id}
     */
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    /**
     * 创建用户
     * POST /api/users
     */
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    /**
     * 更新用户
     * PUT /api/users/{id}
     */
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        return userService.updateUser(id, user);
    }
    /**
     * 删除用户
     * DELETE /api/users/{id}
     */
    @DeleteMapping("/{id}")
    public Map<String, String> deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }
}

服务层

UserService.java

package com.example.demo.service;
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
 * 用户服务类
 */
@Service
public class UserService {
    // 使用内存存储数据(示例)
    private final Map<Long, User> userStore = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    /**
     * 获取所有用户
     */
    public List<User> getAllUsers() {
        return new ArrayList<>(userStore.values());
    }
    /**
     * 根据ID获取用户
     */
    public User getUserById(Long id) {
        return userStore.get(id);
    }
    /**
     * 创建用户
     */
    public User createUser(User user) {
        Long id = idGenerator.getAndIncrement();
        user.setId(id);
        userStore.put(id, user);
        return user;
    }
    /**
     * 更新用户
     */
    public User updateUser(Long id, User user) {
        if (userStore.containsKey(id)) {
            user.setId(id);
            userStore.put(id, user);
            return user;
        }
        throw new RuntimeException("用户不存在");
    }
    /**
     * 删除用户
     */
    public Map<String, String> deleteUser(Long id) {
        userStore.remove(id);
        Map<String, String> result = new HashMap<>();
        result.put("message", "用户删除成功");
        return result;
    }
}

配置文件

application.yml

# 应用配置
server:
  port: 8080                      # 服务器端口
  servlet:
    context-path: /               # 上下文路径
spring:
  application:
    name: spring-boot-demo        # 应用名称
  # 开发环境配置
  devtools:
    remote:
      restart:
        enabled: true             # 启用热部署
# 日志配置
logging:
  level:
    root: INFO                    # 根日志级别
    com.example.demo: DEBUG       # 应用日志级别
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"  # 控制台日志格式
# 自定义配置
app:
  version: 1.0.0
  author: Jason

测试类

DemoApplicationTests.java

package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
    @Test
    void contextLoads() {
        // 测试应用程序上下文加载
    }
}

HelloControllerTest.java

package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerTest {
    @LocalServerPort
    private int port;
    @Autowired
    private TestRestTemplate restTemplate;
    @Test
    public void testHello() {
        ResponseEntity<String> response = restTemplate
            .getForEntity("http://localhost:" + port + "/api/hello", String.class);
        assert response.getStatusCode().is2xxSuccessful();
        assert response.getBody().equals("Hello, Spring Boot!");
    }
}

运行和测试

运行方式

  1. IDE运行:在IDE中直接运行DemoApplication类的main方法

  2. 命令行运行

    # Maven方式
    mvn spring-boot:run
    # 或打包后运行
    mvn clean package
    java -jar target/spring-boot-demo-1.0.0.jar

测试API

启动后访问以下地址测试:

  • http://localhost:8080/api/hello - 基础问候
  • http://localhost:8080/api/hello?name=张三 - 带参数
  • http://localhost:8080/api/users - 获取所有用户
  • POST http://localhost:8080/api/users - 创建用户

curl测试命令

# 测试hello接口
curl http://localhost:8080/api/hello
# 创建用户
curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"张三","age":25,"email":"zhangsan@example.com"}'
# 获取用户列表
curl http://localhost:8080/api/users

关键点说明

  1. @SpringBootApplication:组合注解,包含自动配置和组件扫描
  2. REST Controller:使用@RestController处理HTTP请求
  3. 依赖注入:使用@Autowired自动装配
  4. Lombok:简化POJO代码
  5. 统一配置文件:使用application.yml集中配置
  6. 自动配置:Spring Boot根据依赖自动配置

这个入门案例包含了Spring Boot的核心概念,可以作为学习的基础,您可以根据需求继续扩展,如添加数据库、安全认证、微服务等功能。

抱歉,评论功能暂时关闭!