springboot-项目初始化常用配置

application.properties配置
#mysql配置
spring.datasource.url=jdbc:mysql://localhost/wechat?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=soyeajr
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5

#mybatis配置 注意开启:@MapperScan(basePackages = "com.soyea.mapper")
mybatis.mapper-locations=classpath:mappers/*.xml
#mybatis.type-aliases-package=com.soyea.entity,com.soyea.common.dto,com.hg.common.vo
#mybatis.configuration.cache-enabled=true

#jackson配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8


#应用根路径
server.context-path=/sell
server.port=8080

spring.jpa.show-sql=true
logging.level.org.springframework.web=debug
ResultEnum.java
package com.hg.common.result;

import lombok.Getter;

/**
 * 错误码枚举类
 */
@Getter
public enum ResultEnum {
	//通用模块
	SUCCESS(1, "操作成功"),
	SYSTEM_ERROR(2, "系统出现异常,请联系管理员"),
	PARAM_ERROR(3, "参数不正确");
	
	//其他模块

	private Integer code;
	private String message;

	ResultEnum(Integer code, String message) {
		this.code = code;
		this.message = message;
	}
	
	public static ResultEnum stateOf(int index) {
		for (ResultEnum state : values()) {
			if (state.getCode() == index) {
				return state;
			}
		}
		return null;
	}
}
自定义业务异常
/**
 * 自定义业务异常
 * Created by skh on 2017/12/13
 */
@Getter
public class BizException extends RuntimeException{
	private Integer code;

	public BizException(ResultEnum resultEnum) {
		super(resultEnum.getMessage());
		this.code = resultEnum.getCode();
	}

	public BizException(Integer code, String message) {
		super(message);
		this.code = code;
	}
}
Ajax返回对象
package com.hg.common.result;

import lombok.Data;

import java.io.Serializable;

/**
 * ajax请求返回的对象
 */
@Data
public class AjaxResult
 
   implements Serializable {
	private Integer code;
	private String msg;
	private T data;

	/**
	 * 成功时调用
	 * @param data
	 * @param 
  
    * @return */ public static
   
     AjaxResult
    
      success(T data) { AjaxResult ajaxResult = new AjaxResult(); ajaxResult.setCode(ResultEnum.SUCCESS.getCode()); ajaxResult.setMsg(ResultEnum.SUCCESS.getMessage()); ajaxResult.setData(data); return ajaxResult; } /** * 成功时调用 * @return */ public static AjaxResult success(){ return success(null); } /** * 失败时调用 * @param code * @param msg * @return */ public static AjaxResult error(Integer code, String msg) { AjaxResult ajaxResult = new AjaxResult(); ajaxResult.setCode(code); ajaxResult.setMsg(msg); return ajaxResult; } /** * 失败时调用 * @return */ public static AjaxResult error(ResultEnum resultEnum) { AjaxResult ajaxResult = new AjaxResult(); ajaxResult.setCode(resultEnum.getCode()); ajaxResult.setMsg(resultEnum.getMessage()); return ajaxResult; } }
    
   
  
 
全局异常处理器
package com.hg.common.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.StrUtil;
import com.hg.common.result.AjaxResult;
import com.hg.common.result.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.swing.MenuItemLayoutHelper;

import java.util.List;
import java.util.function.Consumer;

/**
 * 全局异常处理器
 * Created by skh on 2017/12/22
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 处理全局异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public AjaxResult handleException(Exception e) {
		log.error(e.getMessage(), e);
		return AjaxResult.error(ResultEnum.SYSTEM_ERROR.getCode(), ResultEnum.SYSTEM_ERROR.getMessage());
	}

	/**
	 * 处理自定义异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BizException.class)
	@ResponseBody
	public AjaxResult handleBizException(BizException e) {
		log.error(e.getMessage(), e);
		return AjaxResult.error(e.getCode(), e.getMessage());
	}

	/**
	 * 处理参数校验异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public AjaxResult handleBindException(BindException e) {
		List
 
   allErrors = e.getAllErrors();
		List
  
    errorMsgList = CollUtil.newArrayList(); for (ObjectError error : allErrors) { String defaultMessage = error.getDefaultMessage(); errorMsgList.add(defaultMessage); } //拼接所有错误信息 String errorMsg = CollUtil.join(errorMsgList, ","); log.error(ResultEnum.PARAM_ERROR.getMessage() + ":" + errorMsg,e); return AjaxResult.error(ResultEnum.PARAM_ERROR.getCode(), ResultEnum.PARAM_ERROR.getMessage() + ":" + errorMsg); } }
  
 
返回json字符串 null值转空字符串
package com.enz.college.admin.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * 〈返回json空值去掉null和""〉
 */
@Configuration
public class JacksonConfig {
	@Bean
	@Primary
	@ConditionalOnMissingBean(ObjectMapper.class)
	public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
		ObjectMapper objectMapper = builder.createXmlMapper(false).build();

		// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
		// Include.Include.ALWAYS 默认
		// Include.NON_DEFAULT 属性为默认值不序列化
		// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
		// Include.NON_NULL 属性为NULL 不序列化
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

		// 字段保留,将null值转为""
//		objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
//			@Override
//			public void serialize(Object o, JsonGenerator jsonGenerator,
//								  SerializerProvider serializerProvider)
//					throws IOException, JsonProcessingException {
//				jsonGenerator.writeString("");
//				jsonGenerator.writeNull();
//			}
//		});
		return objectMapper;
	}
}
相关代码

相关文章

相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
公众号推荐
   一个健康类的公众号,欢迎关注
小青桔健康