枪战英雄
99.99M · 2026-03-28
自动配置:根据项目的依赖自动配置相关的 Bean
内嵌服务器:Spring Boot 默认提供嵌入式服务器(如 Tomcat、Jetty 或 Undertow),可以直接运行应用
<!-- 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>
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 # 实体类包
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> {
}
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;
}
}
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);
}
}
定义统一返回结果类
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,"用户名已存在,注册失败");
}
}
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());
}
}
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;
}
}