1、跨域配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @description: 跨域配置
* @author: hkl
* @create: 2020-10-30
**/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允许任何域名
corsConfiguration.addAllowedHeader("*"); //允许任何头
corsConfiguration.addAllowedMethod("*"); //允许任何方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注册
return new CorsFilter(source);
}
}
2、全局异常处理
import com.wc.robotapi.common.MessageResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class APIExceptionHandler {
/**
* @description: 全局异常处理配置
* @author: huangkailong
* @create: 2020-10-30
**/
@ExceptionHandler(value =Exception.class)
public MessageResult exceptionHandler(Exception e){
return MessageResult.error(e.getMessage());
}
}
3、使用page分页配置
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
//分页配置
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
4、返回MessageResult对象
package com.wc.robotapi.common;
public class MessageResult<T> {
private boolean Result;
private String ErrorMessage;
private T KeyValue;
public static <T> MessageResult<T> success(T data){
return new MessageResult<T>(data);
}
public static <T> MessageResult<T> success(){
return new MessageResult<T>();
}
public static <T> MessageResult error(String _ErrorMessage){
return new MessageResult<T>(_ErrorMessage);
}
private MessageResult(T data){
this.Result = true;
this.ErrorMessage = "SUCCESS";
this.KeyValue = data;
}
private MessageResult(){
this.Result = true;
this.ErrorMessage = "SUCCESS";
}
private MessageResult(String _ErrorMessage){
// if (_Result) {
// return;
// }
this.Result = false;
this.ErrorMessage = _ErrorMessage;
}
public boolean getResult() {
return Result;
}
public void setResult(Boolean Result) {
this.Result = Result;
}
public String getMessage() {
return ErrorMessage;
}
public void setMessage(String ErrorMessage) {
this.ErrorMessage = ErrorMessage;
}
public T getKeyValue() {
return KeyValue;
}
public void setKeyValue(T KeyValue) {
this.KeyValue = KeyValue;
}
}
5、Mybatis-plus sql日志打印
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl