idea2025构建springboot项目能运行的样例
先创建一个swaggerdemo项目,选择maven,这里使用maven3.9.6,java选择17,jar和war随便选,需要安装lombok插件.
pom.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>swaggerdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>swaggerdemo</name>
<description>Swagger Demo Project</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
spring.application.name=swaggerdemo
# 数据库配置
spring.datasource.url=jdbc:mysql:
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis Plus配置
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.mapper-locations=classpath*:/mapper*.xml
# OpenAPI配置
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
OpenAPIConfig
package com.example.swaggerdemo.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPIConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Swagger Demo API")
.version("1.0")
.description("Swagger Demo 项目接口文档")
.contact(new Contact()
.name("Developer")
.email("developer@example.com")
.url("http://localhost:8080"))
.license(new License().name("Apache 2.0")
.url("http://springdoc.org")));
}
}
AuthController
package com.example.swaggerdemo.controller;
import com.example.swaggerdemo.dto.LoginRequest;
import com.example.swaggerdemo.dto.LoginResponse;
import com.example.swaggerdemo.entity.User;
import com.example.swaggerdemo.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证接口", description = "用户认证相关接口")
public class AuthController {
@Autowired
private UserService userService;
@PostMapping("/login")
@Operation(summary = "用户登录", description = "用户登录接口")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "登录成功"),
@ApiResponse(responseCode = "401", description = "用户名或密码错误")
})
public LoginResponse login(@RequestBody LoginRequest loginRequest) {
LoginResponse response = new LoginResponse();
boolean loginSuccess = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
if (loginSuccess) {
response.setSuccess(true);
response.setMessage("登录成功");
response.setToken("fake-jwt-token");
} else {
response.setSuccess(false);
response.setMessage("用户名或密码错误");
}
return response;
}
@GetMapping("/user/{username}")
@Operation(summary = "根据用户名获取用户信息", description = "根据用户名获取用户详细信息")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "获取成功"),
@ApiResponse(responseCode = "404", description = "用户不存在")
})
public User getUserByUsername(@PathVariable String username) {
return userService.findByUsername(username);
}
@GetMapping("/user")
@Operation(summary = "获取所有用户", description = "获取所有用户接口")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "获取成功"),
@ApiResponse(responseCode = "404", description = "获取失败")
})
public List<User> getAllUsers() {
return userService.selectAllUsers();
}
}
LoginRequest
package com.example.swaggerdemo.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "登录请求参数")
public class LoginRequest {
@Schema(description = "用户名", example = "admin", required = true)
private String username;
@Schema(description = "密码", example = "123456", required = true)
private String password;
}
LoginResponse
package com.example.swaggerdemo.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(name = "登录响应结果")
public class LoginResponse {
@Schema(description = "是否登录成功")
private Boolean success;
@Schema(description = "消息")
private String message;
@Schema(description = "token")
private String token;
}
User
package com.example.swaggerdemo.entity;
import com.baomidou.mybatisplus.annotation.*;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@TableName("user")
@Schema(name = "用户实体")
public class User {
@TableId(value = "id", type = IdType.AUTO)
@Schema(description = "用户ID")
private Long id;
@Schema(description = "用户名")
private String username;
@Schema(description = "密码")
private String password;
@Schema(description = "邮箱")
private String email;
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
private LocalDateTime updateTime;
@TableLogic
@Schema(description = "删除标志(0:未删除, 1:已删除)")
private Integer deleted;
}
UserMapper
package com.example.swaggerdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.swaggerdemo.entity.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
User findByUsername(@Param("username") String username);
User login(@Param("username") String username, @Param("password") String password);
List<User> selectAllUsers();
User selectById(@Param("id") Long id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(@Param("id") Long id);
}
UserService
package com.example.swaggerdemo.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.swaggerdemo.entity.User;
import com.example.swaggerdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
@Autowired
private UserMapper userMapper;
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}
public boolean login(String username, String password) {
User user = userMapper.login(username, password);
return user != null;
}
public List<User> selectAllUsers() {
return userMapper.selectAllUsers();
}
}
SwaggerdemoApplication
package com.example.swaggerdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.swaggerdemo.mapper")
public class SwaggerdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerdemoApplication.class, args);
}
}
resources\mapper\UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.swaggerdemo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.swaggerdemo.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="email" property="email"/>
<result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/>
<result column="deleted" property="deleted"/>
</resultMap>
<sql id="Base_Column_List">
id, username, password, email, create_time, update_time, deleted
</sql>
<select id="findByUsername" parameterType="string" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM user
WHERE username = #{username} AND deleted = 0
</select>
<select id="login" parameterType="map" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM user
WHERE username = #{username} AND password = #{password} AND deleted = 0
</select>
<select id="selectAllUsers" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM user
WHERE deleted = 0
ORDER BY create_time DESC
</select>
<select id="selectById" parameterType="long" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM user
WHERE id = #{id} AND deleted = 0
</select>
<insert id="insertUser" parameterType="com.example.swaggerdemo.entity.User">
INSERT INTO user(username, password, email, create_time, update_time)
VALUES (#{username}, #{password}, #{email}, NOW(), NOW())
</insert>
<update id="updateUser" parameterType="com.example.swaggerdemo.entity.User">
UPDATE user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
update_time = NOW()
</set>
WHERE id = #{id} AND deleted = 0
</update>
<update id="deleteUser" parameterType="long">
UPDATE user
SET deleted = 1, update_time = NOW()
WHERE id = #{id}
</update>
</mapper>
SQL
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(100) NOT NULL COMMENT '密码',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`deleted` int DEFAULT '0' COMMENT '删除标志(0:未删除, 1:已删除)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `user` (`username`, `password`, `email`) VALUES
('admin', '123456', 'admin@example.com'),
('user1', 'password1', 'user1@example.com');