java第一个接口

1.环境准备

  • JDK 17 (Spring Boot 3.x要求)

  • Maven 3.8+

  • IDE (IntelliJ IDEA或VS Code)

2.创建Spring Boot项目

使用Spring Initializr (https://start.spring.io/) 创建项目,选择以下依赖:

  • Spring Web (Spring MVC)

  • Spring Data JPA

  • H2 Database (内存数据库,适合示例)

  • Lombok (简化代码)

3.项目结构

复制代码
src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── demo/
│   │               ├── DemoApplication.java
│   │               ├── controller/
│   │               │   └── UserController.java
│   │               ├── model/
│   │               │   └── User.java
│   │               ├── repository/
│   │               │   └── UserRepository.java
│   │               └── service/
│   │                   └── UserService.java
│   └── resources/
│       ├── application.properties
│       └── data.sql

4.编写代码

实体类 (User.java)

java 复制代码
package com.example.demo.model;

import jakarta.persistence.*;
import lombok.*;

@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(unique = true, nullable = false)
    private String email;
}

仓库接口 (UserRepository.java)

java 复制代码
package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

服务层 (UserService.java)

java 复制代码
package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public User createUser(User user) {
        return userRepository.save(user);
    }
    
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }
}

控制器 (UserController.java)

java 复制代码
package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }
    
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

配置文件 (application.properties)

复制代码
# 启用H2控制台
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# 数据库配置
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true

初始化数据 (data.sql)

sql 复制代码
INSERT INTO users (name, email) VALUES 
('张三', 'zhangsan@example.com'),
('李四', 'lisi@example.com');

5.运行和测试

  1. 启动应用:运行DemoApplication.java中的main方法

  2. 访问H2控制台:http://localhost:8080/h2-console

    • JDBC URL: jdbc:h2:mem:testdb

    • User Name: sa

    • Password: (空)

  3. 测试API:

特性:

  1. Spring Boot 3:最新的Spring框架版本

  2. Jakarta EE 9+:取代了旧的javax包

  3. Lombok:减少样板代码

  4. H2内存数据库:快速开发测试

  5. RESTful风格API:符合现代API设计规范

  6. 分层架构:Controller-Service-Repository

  7. 依赖注入:通过构造函数注入

相关推荐
lly2024061 小时前
Bootstrap 警告框
开发语言
2601_949146532 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧2 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX2 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01032 小时前
C++课后习题训练记录Day98
开发语言·c++
爬山算法3 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7253 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎3 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄3 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
YUJIANYUE3 小时前
PHP纹路验证码
开发语言·php