详细介绍:Spring Boot 应用示例

完整的最小 Spring Boot 应用示例

1. 启动类(必须)

Spring Boot 需要一个启动类,通常放在 src/main/java 的根包或合适的包路径下:

package com.socpk.springapp;  // 建议和 Controller 在同一个父包下
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication  // 核心注解,启用自动配置、组件扫描等
public class SpringAppApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAppApplication.class, args);
}
}
2. Controller
package com.socpk.springapp.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/")
public String hello() {
return "Hello world!CodeArts";
}
@RequestMapping("/codearts")
public String codearts() {
return "Hello CodeArts!";
}
}

有人问,项目是否需要 Service、Entity 等?

  1. Controller 可以直接返回数据(如你的例子),不需要 Service 或 Entity。

  2. 如果涉及业务逻辑(如数据库查询、计算等),建议:

    • Service 层:处理业务逻辑(如 UserService)。

    • Repository/DAO 层:数据库操作(如 JpaRepository)。

    • Entity 类:数据库表映射(如 User.java)。

示例:增加 Service(可选)
package com.socpk.springapp.service;
import org.springframework.stereotype.Service;
@Service  // 声明为 Spring 管理的 Service
public class HelloService {
public String getWelcomeMessage() {
return "Welcome from Service!";
}
}
在 Controller 中使用 Service
@RestController
public class HelloController {
@Autowired  // 自动注入 Service
private HelloService helloService;
@RequestMapping("/service-message")
public String serviceMessage() {
return helloService.getWelcomeMessage();
}
}

总结

  • 必须:启动类 @SpringBootApplication + Controller。

  • 可选:Service(业务逻辑)、Repository(数据库)、Entity(数据模型)。

  • 你的例子 可以直接运行,不需要 Service 或 Entity。

运行后访问:

  • http://localhost:8080/ → 返回 HTML

  • http://localhost:8080/codearts → 返回纯文本


进阶版:

下面我们可以在这个基础上增加 YAML 配置实体类(Entity)Repository(JPA) 和 Service 层,实现 CRUD(增删改查) 功能。

1. 项目结构调整

src/main/
├── java/
│   ├── com.socpk.springapp/
│   │   ├── SpringAppApplication.java        # 启动类
│   │   ├── controller/
│   │   │   └── UserController.java         # 控制器
│   │   ├── entity/
│   │   │   └── User.java                   # 实体类
│   │   ├── mapper/
│   │   │   └── UserMapper.java             # MyBatis-Plus Mapper
│   │   └── service/
│   │       ├── UserService.java            # 服务接口
│   │       └── impl/
│   │           └── UserServiceImpl.java    # 服务实现
└── resources/
├── application.yml                     # YAML 配置
└── mapper/
└── UserMapper.xml                  # MyBatis XML 映射文件(可选)

2. 修改 application.yml(MySQL + MyBatis-Plus)

yaml:

server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot_db?useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456  # 替换为你的 MySQL 密码
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 打印 SQL 日志
global-config:
db-config:
id-type: auto  # 主键自增

注意

  • 提前创建 MySQL 数据库(如 springboot_db)。

  • 如果不想用 XML 映射文件,可以全部用注解方式(后面示例会展示)。


3. 实体类 User.java(MyBatis-Plus 注解)

package com.socpk.springapp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("users")  // 指定表名
public class User {
@TableId(type = IdType.AUTO)  // 自增主键
private Long id;
private String name;
private String email;
// 构造方法、Getter、Setter
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getter & Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

4. Mapper 接口 UserMapper.java

package com.socpk.springapp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.socpk.springapp.entity.User;
public interface UserMapper extends BaseMapper {
// 继承 BaseMapper 后,已自带 CRUD 方法
// 可以自定义方法(如需要)
User findByEmail(String email);
}

说明

  • BaseMapper 已经提供了 insert()selectById()updateById()deleteById() 等方法。

  • 自定义方法 findByEmail 需要在 UserMapper.xml 或使用 @Select 注解实现。


5. Service 层

(1)接口 UserService.java

package com.socpk.springapp.service;
import com.socpk.springapp.entity.User;
import java.util.List;
public interface UserService {
User createUser(User user);
List getAllUsers();
User getUserById(Long id);
User updateUser(User user);
boolean deleteUser(Long id);
}

(2)实现类 UserServiceImpl.java

package com.socpk.springapp.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.socpk.springapp.entity.User;
import com.socpk.springapp.mapper.UserMapper;
import com.socpk.springapp.service.UserService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
@Override
public User createUser(User user) {
baseMapper.insert(user);  // MyBatis-Plus 的插入方法
return user;
}
@Override
public List getAllUsers() {
return baseMapper.selectList(null);  // 查询所有
}
@Override
public User getUserById(Long id) {
return baseMapper.selectById(id);
}
@Override
public User updateUser(User user) {
baseMapper.updateById(user);
return user;
}
@Override
public boolean deleteUser(Long id) {
return baseMapper.deleteById(id) > 0;
}
}

6. Controller 层 UserController.java

package com.socpk.springapp.controller;
import com.socpk.springapp.entity.User;
import com.socpk.springapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@GetMapping
public List getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PutMapping
public User updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
@DeleteMapping("/{id}")
public boolean deleteUser(@PathVariable Long id) {
return userService.deleteUser(id);
}
}

7. 测试 API

使用 Postman 或 curl 测试:

操作HTTP 方法请求路径示例请求体(JSON)
新增用户POSThttp://localhost:8080/api/users{"name": "Alice", "email": "alice@example.com"}
查询所有GEThttp://localhost:8080/api/users-
查询单个GEThttp://localhost:8080/api/users/1-
更新用户PUThttp://localhost:8080/api/users{"id": 1, "name": "Bob", "email": "bob@example.com"}
删除用户DELETEhttp://localhost:8080/api/users/1-

8. 关键依赖

  1. 新增 mybatis-plus-boot-starter

    MySQL 驱动依赖:
    • mysql
      mysql-connector-java
      8.0.28
  2. MyBatis-Plus 优势

    • 无需写 SQL(基本 CRUD 已内置)。

    • 支持 Lambda 查询(如 QueryWrapper<User>().lambda().eq(User::getEmail, "xxx"))。

  3. MySQL 配置

    • 确保数据库已创建,账号密码正确。

posted on 2025-10-11 15:29  slgkaifa  阅读(13)  评论(0)    收藏  举报

导航