跳至主要內容

utils工具类封装

杨轩-国实信息大约 3 分钟framework

git地址:

http://10.16.202.103:8089/component/component-ser/gosci-tech-utilsopen in new window

通用工具类

项目中,如果使用通用工具类库能够实现功能,那么就应该避免在开发过程中重复造轮子的行为,常用的通用工具类有以下这些:

<!-- Java Servlet  -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <scope>provided</scope>
</dependency>

<!-- 简化Java代码工具类 -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>

<!-- 一个国产的Java基础工具类 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
</dependency>

<!-- Googles开源的JAVA工具类库 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
</dependency>

<!-- 阿里的JSON工具类库 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>

<!-- Api文档工具类库 -->
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
</dependency>

<!-- 入参验证工具类库 -->
<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

上面这些类库基本上所有项目都能用到,下面这些中间件工具类相对功能独立,可根据使用场景按需添加:

<!-- 权限 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
</dependency>
<!-- 权限 Oauth2 -->
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
</dependency>
<!-- 权限 令牌秘文 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
</dependency>
<!-- ORM -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
</dependency>
<!-- MQ -->
<dependency>
    <groupId>org.apache.rocketmq</groupId>
    <artifactId>rocketmq-client</artifactId>
</dependency>
<!-- swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 工作流 -->
<dependency>
    <groupId>org.flowable</groupId>
    <artifactId>flowable-engine</artifactId>
</dependency>
<!-- 数据库连接池 -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
</dependency>
<!-- Redis -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
</dependency>
<!-- 导出Excel工具类库 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
</dependency>

封装功能模块

集合类型转换

实例:

@Test
public void test(){
    List<UserInfo> list=new ArrayList<UserInfo>(){{
        add(new UserInfo("Hydra",18));
        add(new UserInfo("Hydra2",28));
    }};
    
    List<UserInfoCopy> transfer = ConvertUtil.transfer(list,
            userInfo -> BeanUtil.copyProperties(userInfo, UserInfoCopy.class));
    log.info(transfer.toString());
}

@Data
@AllArgsConstructor
static class UserInfo {
    private String name;
    private Integer age;
}

@Data
static class UserInfoCopy {
    private String name;
}

异常处理

CheckedException转换为UncheckedException,避免层层向上抛出:

try{
    //...
} catch (Exception e) {
   throw ExceptionUtil.unchecked(e);
}

将异常转化为String:

ExceptionUtil.getStackTraceAsString(e);

http

封装了常用http操作,通过链式请求方式简化请求、参数配置、结果转换。示例:

@Test
public void getTest() {
    Map<String, Object> params = new HashMap<>();
    params.put("hello", "world");
    Map<String, Object> stringObjectMap = HttpRequest
            .get("http://10.182.71.237:8001/bms/operation/login/auto")
            .queryMap(params)
            .log(LogLevel.BASIC)
            .connectTimeout(Duration.ofSeconds(120))
            .readTimeout(Duration.ofSeconds(120))
            .execute()
            .asMap(JsonNode.class);
    log.info(JsonUtils.toPrettyString(stringObjectMap));
}

excel操作

集成easyPoi

封装了常见的excel操作,如excel、csv的导入导出功能。

实体类需要添加注解@ExcelTarget,属性字段上添加@Excel

@Data
@NoArgsConstructor
@AllArgsConstructor
@ExcelTarget("UserEntity")
public class UserEntity {

    @Excel(name = "用户id",orderNum = "0",width = 18)
    private Long userId;

    @Excel(name = "姓名",orderNum = "1",width = 20)
    private String name;
}

单sheet页excel导出:

@Test
public void exportTest(){
    List<UserEntity> list=initData();
    EasypoiUtil.exportExcel(list, UserEntity.class,"F:\\usr\\tmp\\test.xlsx","用户","用户信息");
	//EasypoiUtil.exportExcel(list, UserEntity.class,"F:\\usr\\tmp\\test.xlsx","用户",null);
}

多sheet页excel导出:

@Test
public void multiSheet(){
    List<UserEntity> list=initData();
    List<UserEntity> list2=initData();
    List<UserEntity> list3=initData();

    EasypoiDataParam<UserEntity> param1=new EasypoiDataParam(list,UserEntity.class,"用户表1");
    EasypoiDataParam<UserEntity> param2=new EasypoiDataParam(list2,UserEntity.class,"用户表2");
    EasypoiDataParam<UserEntity> param3=new EasypoiDataParam(list3,UserEntity.class,"用户表3");

    List<EasypoiDataParam> params = new ArrayList<EasypoiDataParam>(){{
        add(param1);
        add(param2);
        add(param3);
    }};

    EasypoiUtil.exportMultiSheetExcel(params,"F:\\usr\\tmp\\test2.xlsx");
}

excel导入:

public void importTest1(){
    List<UserEntity> list = EasypoiUtil.importExcel("F:\\usr\\tmp\\test.xlsx", UserEntity.class);
    System.out.println(list.toString());
}

@Test
public void importTest2(){
    List<UserEntity> list = EasypoiUtil.importExcel(new File("F:\\usr\\tmp\\test.xlsx"), UserEntity.class);
    System.out.println(list.toString());
}

@Test
public void importCsv(){
    List<UserEntity> list = EasypoiUtil.importExcel("F:\\usr\\tmp\\test.csv", UserEntity.class);
    System.out.println(list.toString());
}

另外,支持从流导入、导出到流的功能。从流的导入,兼容了minio的接口:

public void minioExcelTest(){
    byte[] object = minioObjectService.getObject(minioProperties.getBucket(), "test.xlsx");
    List<UserEntity> userEntities = EasypoiUtil.importExcel(object, UserEntity.class);
    System.out.println(userEntities.toString());
}

Json工具类

封装jackson常用操作,包括序列化、反序列化操作,具体可以看一下readtoStringtoPrettyString等方法。

后续补充示例

获取单例ObjectMapper,避免重复创建造成性能损耗:

ObjectMapper objectMapper = JsonUtils.getObjectMapper();

IP

获取请求的ip地址。

反射

  • 通过反射调用对象属性相应get方法
  • 通过反射调用对象属性相应set方法

spring

SpringUtils工具类,方便通过静态方法获取bean实例,例如可以这样获取一个bean:

FastDfsUtil fastDfsUtil = SpringUtils.getBean(FastDfsUtil.class);

SM加解密

生成公钥和私钥:

Sm2Util.createPrivateKey();
/*
*私钥: MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgnfYnEiUVjjNW3qWvEWHUX8OScDvCfy9KbsSqAF+/xM2gCgYIKoEcz1UBgi2hRANCAARAmuFPgVaKNlwPlP8sUjJX+lPu0tYThzt29l/7tA9IjpFzDPvRt//hMIWItbS81TM+RsshrTocJDX+7LF9MmtL
*公钥: MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEQJrhT4FWijZcD5T/LFIyV/pT7tLWE4c7dvZf+7QPSI6Rcwz70bf/4TCFiLW0vNUzPkbLIa06HCQ1/uyxfTJrSw==
*/

加密:

String text = "123456";
String enStr = Sm2Util.encryptBase64(text, Sm2KeyEnum.AUTH_PASSWORD.getPublicKey());

//BDYygIrEeJynuxOsZrCYv1PluRpFq5nhjOtiAX6Djo5/NVHTni0HyuZ6/7ukdIKpm/xWnA6A6d+5Mj4/sFWajeFFQXwDLjQZKMe/XOCIelTJCSfNcBFAyeyvZRFQuE4SxXIWYbv4JQ==

解密:

String value="BDYygIrEeJynuxOsZrCYv1PluRpFq5nhjOtiAX6Djo5/NVHTni0HyuZ6/7ukdIKpm/xWnA6A6d+5Mj4/sFWajeFFQXwDLjQZKMe/XOCIelTJCSfNcBFAyeyvZRFQuE4SxXIWYbv4JQ==";
String decStr = Sm2Util.decryptBase64OrHex(value, Sm2KeyEnum.AUTH_PASSWORD.getPublicKey());

//123456