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. 依赖注入:通过构造函数注入

相关推荐
毕设源码-朱学姐4 小时前
【开题答辩全过程】以 工厂能耗分析平台的设计与实现为例,包含答辩的问题和答案
java·vue.js
喵了meme5 小时前
C语言实战4
c语言·开发语言
码界奇点5 小时前
Python从0到100一站式学习路线图与实战指南
开发语言·python·学习·青少年编程·贴图
9ilk5 小时前
【C++】--- 特殊类设计
开发语言·c++·后端
sali-tec6 小时前
C# 基于halcon的视觉工作流-章68 深度学习-对象检测
开发语言·算法·计算机视觉·重构·c#
Spring AI学习6 小时前
Spring AI深度解析(9/50):可观测性与监控体系实战
java·人工智能·spring
java1234_小锋7 小时前
Spring IoC的实现机制是什么?
java·后端·spring
生骨大头菜7 小时前
使用python实现相似图片搜索功能,并接入springcloud
开发语言·python·spring cloud·微服务
绝不收费—免费看不了了联系我7 小时前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
xqqxqxxq7 小时前
背单词软件技术笔记(V2.0扩展版)
java·笔记·python