1、Spring Boot 核心内容

1.1 特性

  • 自动配置:根据项目的依赖自动配置相关的 Bean

  • 内嵌服务器:Spring Boot 默认提供嵌入式服务器(如 Tomcat、Jetty 或 Undertow),可以直接运行应用

1.2 常用注解

  1. @SpringBootApplication 注解:一个组合注解,包含以下三个注解:
  • @Configuration:声明这是一个配置类,Spring 容器会扫描并处理该类中的配置。
  • @EnableAutoConfiguration:启用 Spring Boot 的自动配置功能。
  • @ComponentScan:启用组件扫描,查找并注册所有带有 @Component、@Service、@Repository 等注解的 Bean
  1. @RestController:简化 @Controller 和 @ResponseBody 的使用,用于定义 RESTful API 控制器。
  2. @Value:用于从配置文件中获取值并注入到类中
  3. @Autowired:自动注入 Bean,Spring 会根据类型自动装配依赖。

2、创建Spring Boot项目并整合MyBatis-Plus

2.1 修改pom.xml,添加MuBatis-Plus依赖

<!-- Spring Boot Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- MyBatis-Plus Starter -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.1</version>
</dependency>

2.2 配置application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/example_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
    # HikariCP连接池配置
    hikari:
      maximum-pool-size: 10
      minimum-idle: 5
      connection-timeout: 30000

# MyBatis-Plus配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 打印SQL日志
    map-underscore-to-camel-case: true                      # 驼峰映射
  global-config:
    db-config:
      id-type: auto                                          # 主键自增
      logic-delete-field: deleted                            # 逻辑删除字段
      logic-delete-value: 1
      logic-not-delete-value: 0
  mapper-locations: classpath:/mapper/*.xml                  # mapper.xml位置
  type-aliases-package: com.example.entity                  # 实体类包

2.3 创建实体类entity和Mapper接口

package com.example.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.util.Date;

@Data  // Lombok自动生成getter/setter/toString等
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    @TableField("real_name")
    private String realName;
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private Date createTime;
}
package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

2.4 创建Service层和Controller层

package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    //添加自定义的方法
    User login(String username, String password);
    boolean register(User user);
}
package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * POST /api/users/login
     * Body: { "username": "admin", "password": "123456" }
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        User user = userService.login(username, password);
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("data", user);
        } else {
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    /**
     * 用户注册
     * POST /api/users/register
     * Body: { "username": "test", "password": "123", "realName": "测试" }
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        boolean success = userService.register(user);
        Map<String, Object> result = new HashMap<>();
        if (success) {
            result.put("code", 200);
            result.put("message", "注册成功");
        } else {
            result.put("code", 400);
            result.put("message", "用户名已存在");
        }
        return result;
    }
}

2.5 完善Spring Boot启动类

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper")  // 扫描Mapper接口
public class HospitalSystemApplication {
    public static void main(String[] args) {
        SpringApplication.run(HospitalSystemApplication.class, args);
    }
}

3、完善基础架构(统一返回格式 + 全局异常处理 + MyBatis-Plus分页插件)

3.1 统一返回格式

定义统一返回结果类

package com.example.common;

import lombok.Data;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("success");
        result.setData(data);
        return result;
    }

    public static <T> Result<T> error(Integer code, String message) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
}

修改Controller使用统一返回格式

@PostMapping("/login")
public Result<User> login(@RequestBody Map<String, String> loginInfo) {
    String username = loginInfo.get("username");
    String password = loginInfo.get("password");
    User user = userService.login(username, password);
    if (user != null) {
        return Result.success(user);
    } else {
        return Result.error(401, "用户名或密码错误");
    }
}

@PostMapping("/register")
public Result<User> register(@RequestBody User user){
    boolean success = userService.register(user);

    if(success) {
        return Result.success(user);
    } else {
        return Result.error(400,"用户名已存在,注册失败");
    }
}

3.2 全局异常处理

package com.example.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        return Result.error(500, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        e.printStackTrace();
        return Result.error(500, "系统错误:" + e.getMessage());
    }
}

3.3 MyBatis-Plus分页插件配置

package com.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:alixiixcom@163.com