相关依赖

Mybatis-Plus

按照常规创建一个Spring的项目,随后引入mybatis-plus,在Gradle下引入添加以下即可:

implementation 'com.baomidou:mybatis-plus-boot-starter:+'

注意不可以省略后面的+号。

程序配置

Server

可自定义端口,如下:

server:  
	port: 8090

Spring

数据源

数据源可参考下面进行配置:

spring:  
  datasource:  
    url: jdbc:postgresql://127.0.0.1:5432/testdb  
    username: u01  
    password: xhdWt0enz3U3Gwz90urS56t0QQ6IoZ

Spring 相关操作

自动SQL执行

参考下面配置:

spring:  
  sql:  
    init:  
      schema-locations: classpath:sql/init_db.sql  
      mode: always

静态资源放行

SecurityConfig中配置以下:

@Bean  
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {  
    httpSecurity  
		    .xxxx
			.xxxx
            .authorizeHttpRequests(auth -> auth.requestMatchers(new String[]{"/static/**"}).permitAll())
            .xxxxx
            .xxxxx;
    return httpSecurity.build();  
}

全局异常处理

全局异常

package com.example.webtest.exception;  
  
public class BaseException extends RuntimeException{  
  
    private int statusCode;  
  
    public BaseException(int statusCode, String message) {  
        super(message);  
        this.statusCode = statusCode;  
    }  
  
    public int getStatusCode() {  
        return statusCode;  
    }  
  
    public void setResponseCode(int statusCode) {  
        this.statusCode = statusCode;  
    }
}

注册异常处理器

package com.example.webtest.handler.exception;  
  
import com.example.webtest.exception.BaseException;  
import com.example.webtest.entity.response.ResultDTO;  
import jakarta.servlet.http.HttpServletResponse;  
import org.springframework.web.bind.annotation.ExceptionHandler;  
import org.springframework.web.bind.annotation.RestControllerAdvice;  
  
@RestControllerAdvice  
public class BaseExceptionHandler {  
  
    @ExceptionHandler(BaseException.class)  
    public ResultDTO handleGlobalException(HttpServletResponse response, BaseException e) {  
        response.setStatus(e.getStatusCode());  
        return ResultDTO.error(e.getStatusCode(), e);  
    }  
}

@RestControllerAdvice@ControllerAdvice@ResponseBody