返回

构建属于你的SpringBoot项目脚手架

后端

搭建SpringBoot项目脚手架:快速上手指南

在软件开发领域,使用脚手架可以极大地加快项目的启动和进行。本文将指导你如何构建一个功能丰富的SpringBoot项目脚手架,为你提供一个强大的开发基础。

搭建SpringBoot项目

  1. 创建一个新的SpringBoot项目

你可以使用Spring Initializr或命令行工具创建项目。使用以下命令行命令:

mvn spring-boot:run
  1. 添加mybatis依赖

在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
  1. 配置数据库连接

在application.properties文件中配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456

创建Model类

在src/main/java/com/example/demo/model包下创建Model类:

package com.example.demo.model;

public class User {

    private Long id;
    private String name;
    private String email;

    // getters and setters
}

创建Mapper接口

在src/main/java/com/example/demo/mapper包下创建Mapper接口:

package com.example.demo.mapper;

import com.example.demo.model.User;

public interface UserMapper {

    User selectById(Long id);
    int insert(User user);
    int update(User user);
    int delete(Long id);
}

创建Service类

在src/main/java/com/example/demo/service包下创建Service类:

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.mapper.UserMapper;

public class UserService {

    private UserMapper userMapper;

    public User selectById(Long id) {
        return userMapper.selectById(id);
    }
    public int insert(User user) {
        return userMapper.insert(user);
    }
    public int update(User user) {
        return userMapper.update(user);
    }
    public int delete(Long id) {
        return userMapper.delete(id);
    }
}

创建Controller类

在src/main/java/com/example/demo/controller包下创建Controller类:

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User selectById(@PathVariable Long id) {
        return userService.selectById(id);
    }
    @PostMapping
    public int insert(@RequestBody User user) {
        return userService.insert(user);
    }
    @PutMapping
    public int update(@RequestBody User user) {
        return userService.update(user);
    }
    @DeleteMapping("/{id}")
    public int delete(@PathVariable Long id) {
        return userService.delete(id);
    }
}

统一异常处理

在src/main/java/com/example/demo/config包下创建ExceptionControllerAdvice类:

package com.example.demo.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(HttpServletRequest request, Exception ex) {
        return "系统错误,请联系管理员!";
    }
}

日志打印

在src/main/java/com/example/demo/config包下创建LogbackConfigurer类:

package com.example.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LogbackConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(LogbackConfigurer.class);

    @Autowired
    private Appender appender;

    public void addAppender() {
        logger.info("添加日志Appender");
        // 添加Appender
    }
}

响应体

在src/main/java/com/example/demo/config包下创建WebMvcConfigurerAdapter类:

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class WebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 使用fastjson作为json解析器
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastJsonHttpMessageConverter);
    }
}

结语

搭建一个SpringBoot项目脚手架不仅可以简化项目的启动,还可以提高开发效率和一致性。本文提供的步骤将指导你构建一个功能强大的脚手架,它集成了mybatis、统一异常处理、日志打印和响应体等常用功能。现在,你可以利用这个脚手架专注于业务逻辑的开发,节省时间和精力。

常见问题解答

  1. 如何使用这个SpringBoot项目脚手架?
    • 克隆或下载脚手架的代码库。
    • 根据你的项目需求,修改application.properties文件中的配置。
    • 根据需要创建和配置额外的Model、Mapper、Service和Controller类。
  2. 如何自定义异常处理?
    • 在ExceptionControllerAdvice类中重写handleException()方法。
    • 自定义错误消息或实现不同的异常处理逻辑。
  3. 如何启用日志打印?
    • 实现Appender接口并将其添加到LogbackConfigurer类的addAppender()方法中。
  4. 如何更改默认的响应体格式?
    • 在WebMvcConfigurerAdapter类的configureMessageConverters()方法中修改FastJsonConfig。
  5. 这个脚手架是否可以与其他框架或库一起使用?
    • 是的,这个脚手架可以与Spring Security、Spring Data JPA或其他框架和库一起使用。