java开发中常见的工具类,方法等(持续更新)

1.获取当前线程用户信息:

/**
 * 工具类向threadLocal存储诗句
 */
public class UserHolder {
    private static ThreadLocal t1 =new ThreadLocal<>();

    //将用户对象,存入
    public static void set(User user){
        t1.set(user);
    }

    //当前线程获取用户对象
    public static User get(){
        return t1.get();
    }

    //当前线程获取用户id
    public static Long getUserId(){
        return t1.get().getId();
    }
    //获取当前用户手机号
    public static String getMobile(){
        return t1.get().getMobile();
    }

    public static void remove(){
        t1.remove();
    }
}

2.获取list集合中的id集合:

//先判断users集合是否为空

if(!CollUtil.isEmpty(users)){

List userIds = CollUtil.getFieldValues(users, "userId", Long.class);

}

3.拷贝内容到具有相同成员变量的类中

BeanUtils.copyProperties(item, vo);//将item内容拷贝到新建的vo对象中

4.获取随机不重复的ID

UUID.randomUUID().toString()

5.通用微服务返回类

public class ResponseResult implements Serializable {
    private String host; // IP
    private Integer code = 200;  // 状态码
    private String errorMessage;  // 提示信息
    private T data;  // 数据 Object
    (get...set...)
}

6.分页通用返回

public class PageResponseResult extends ResponseResult {
    private Integer currentPage;
    private Integer size;
    private Integer total;
​
    public PageResponseResult(Integer currentPage, Integer size, Integer total) {
        this.currentPage = currentPage;
        this.size = size;
        this.total = total;
    }
     // set/get 代码省略
}

7.通用的异常枚举

public enum AppHttpCodeEnum {
    // 成功段0
    SUCCESS(0,"操作成功"),
    // 登录段1~50
    NEED_LOGIN(1,"需要登录后操作"),
    LOGIN_PASSWORD_ERROR(2,"密码错误"),
    // TOKEN50~100
    TOKEN_INVALID(50,"无效的TOKEN"),
    TOKEN_EXPIRE(51,"TOKEN已过期"),
    TOKEN_REQUIRE(52,"TOKEN是必须的"),
    // SIGN验签 100~120
    SIGN_INVALID(100,"无效的SIGN"),
    SIG_TIMEOUT(101,"SIGN已过期"),
    // 参数错误 500~1000
    PARAM_REQUIRE(500,"缺少参数"),
    PARAM_INVALID(501,"无效参数"),
    PARAM_IMAGE_FORMAT_ERROR(502,"图片格式有误"),
    SERVER_ERROR(503,"服务器内部错误"),
    // 数据错误 1000~2000
    DATA_EXIST(1000,"数据已经存在"),
    AP_USER_DATA_NOT_EXIST(1001,"ApUser数据不存在"),
    DATA_NOT_EXIST(1002,"数据不存在"),
    // 数据错误 3000~3500
    NO_OPERATOR_AUTH(3000,"无权限操作");
​
    int code;
    String errorMessage;
​
    AppHttpCodeEnum(int code, String errorMessage){
        this.code = code;
        this.errorMessage = errorMessage;
    }
​
    public int getCode() {
        return code;
    }
​
    public String getErrorMessage() {
        return errorMessage;
    }
}

8.SpringBoot自动配置功能

资源目录resources文件夹下添加

META-INF/spring.factories 文件:org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 要自动装配的配置类

如:org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.test.knife4j.config.Swagger2Configuration

只要引入当前配置类的模块依赖,SpringBoot启动时就会自动加载该配置类

9.微服务全局处理异常

@Slf4j
@Configuration
@RestControllerAdvice   // Springmvc 异常处理拦截注解
public class ExceptionCatch {
    /**
     * 解决项目中所有的异常拦截
     * @return
     */
    @ExceptionHandler(Exception.class)  // exception 所有子类
    public ResponseResult exception(Exception ex) {
        ex.printStackTrace();
        // 记录日志
        log.error("ExceptionCatch ex:{}", ex);
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "您的网络异常,请稍后重试");
    }

    /**
     * 拦截自定义异常
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException ex) {
        ex.printStackTrace();
        log.error("CustomException ex:{}", ex);
        AppHttpCodeEnum codeEnum = ex.getAppHttpCodeEnum();
        return ResponseResult.errorResult(codeEnum);
    }
}

@ControllerAdvice 控制器增强注解

@ExceptionHandler 异常处理器 与上面注解一起使用,可以拦截指定的异常信息

META-INF/spring.factories 配置文件中添加:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\该类的位置

自定义异常自己申明就可以了

10.将集合中的每个元素进行修改

例:

  records是分页查询出来的Dish集合

List list = records.stream().map((item) -> {
    DishDto dishDto = new DishDto();
    BeanUtils.copyProperties(item, dishDto);
    Long categoryId = item.getCategoryId();
    //根据Id查询category对象 然后获得name
    Category category = categoryService.getById(categoryId);
    //获取到name并封装进dishDto
    String categoryName = category.getName();
    dishDto.setCategoryName(categoryName);

    return dishDto;

}).toList();

11.MybatisPlus分页插件:

@Bean
 public PaginationInterceptor paginationInterceptor(){
    return new PaginationInterceptor();
}

12.MybatisPlus自动填充字段

@Data
public abstract class BasePojo implements Serializable {

    @TableField(fill = FieldFill.INSERT) //自动填充
    private Date created;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updated;

}

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object created = getFieldValByName("created", metaObject);
        if (null == created) {
            //字段为空,可以进行填充
            setFieldValByName("created", new Date(), metaObject);
        }

        Object updated = getFieldValByName("updated", metaObject);
        if (null == updated) {
            //字段为空,可以进行填充
            setFieldValByName("updated", new Date(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新数据时,直接更新字段
        setFieldValByName("updated", new Date(), metaObject);
    }
}

13.用流的方式过滤集合,过滤出在map中有key的内容,findFirst表示找到第一个就够了,orRlse表示如果没找到就设置为null

List deptList = JSONArray.parseArray(departIds, Integer.class);
Integer deptId = deptList.stream().filter(deptNameMap::containsKey).findFirst().orElse(null);

你可能感兴趣的:(java,jvm,开发语言)