Java公共模块案例如何封装

wen java案例 28

本文目录导读:

Java公共模块案例如何封装

  1. 工具类模块封装
  2. 统一返回结果封装
  3. 通用异常处理
  4. 公共配置模块
  5. 通用分页模型
  6. Maven模块结构
  7. 使用示例

我来介绍几种常见的Java公共模块封装方式及案例:

工具类模块封装

String工具类

package com.example.common.util;
import org.apache.commons.lang3.StringUtils;
/**
 * 字符串工具类
 */
public class StringUtil {
    /**
     * 驼峰转下划线
     */
    public static String camelToUnderline(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_").append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    /**
     * 手机号脱敏
     */
    public static String maskPhone(String phone) {
        if (StringUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
}

统一返回结果封装

package com.example.common.response;
import lombok.Data;
/**
 * 统一返回结果
 */
@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;
    private Long timestamp;
    private Result() {
        this.timestamp = System.currentTimeMillis();
    }
    // 成功
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("success");
        result.setData(data);
        return result;
    }
    // 失败
    public static <T> Result<T> error(Integer code, String message) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
    // 带数据的失败
    public static <T> Result<T> error(Integer code, String message, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }
}

通用异常处理

package com.example.common.exception;
import com.example.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 业务异常
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常:", e);
        return Result.error(e.getCode(), e.getMessage());
    }
    // 参数校验异常
    @ExceptionHandler(ValidationException.class)
    public Result<Void> handleValidationException(ValidationException e) {
        log.error("参数校验异常:", e);
        return Result.error(400, e.getMessage());
    }
    // 运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result<Void> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常:", e);
        return Result.error(500, "服务器内部错误");
    }
}

公共配置模块

package com.example.common.config;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
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;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * 公共配置
 */
@Configuration
public class CommonConfig {
    // 时间序列化配置
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        return builder -> {
            builder.serializerByType(LocalDateTime.class, 
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        };
    }
    // CORS配置
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

通用分页模型

package com.example.common.model;
import lombok.Data;
import java.util.List;
/**
 * 分页结果
 */
@Data
public class PageResult<T> {
    private List<T> records;
    private long total;
    private long pageSize;
    private long pageNum;
    private long pages;
    public static <T> PageResult<T> of(List<T> records, long total, long pageNum, long pageSize) {
        PageResult<T> result = new PageResult<>();
        result.setRecords(records);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setPages((total + pageSize - 1) / pageSize);
        return result;
    }
}

Maven模块结构

<!-- common模块的pom.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent-project</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>common</artifactId>
    <version>1.0.0</version>
    <name>common</name>
    <description>公共模块</description>
    <dependencies>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 工具类 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

使用示例

// 在其他模块中使用
@Service
public class UserService {
    public Result<UserVO> getUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        UserVO vo = new UserVO();
        vo.setPhone(StringUtil.maskPhone(user.getPhone()));
        return Result.success(vo);
    }
    public PageResult<UserVO> listUsers(int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> result = userMapper.selectPage(page, null);
        List<UserVO> vos = result.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
        return PageResult.of(vos, result.getTotal(), pageNum, pageSize);
    }
}

这样的封装方式具有以下优点:

  • 复用性强:公共代码集中管理
  • 统一规范:返回格式、异常处理统一
  • 易于维护:修改公共逻辑只需改动一处
  • 减少重复:避免各模块重复造轮子

抱歉,评论功能暂时关闭!