You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java/Spring中基于类别动态访问JSON属性的通用设计咨询

基于Spring的可配置Category处理方案

核心设计思路

采用策略模式+配置化映射的方式,将不同Category的JSON取值规则与业务处理逻辑完全解耦:

  • 用配置文件(或数据库)维护Category与JSON路径、处理Bean的映射关系
  • 每个Category对应独立的业务处理类,实现统一接口
  • 通过调度器根据Category自动匹配配置,解析JSON取值并调用对应处理逻辑

具体实现步骤

1. 引入依赖(可选,用JsonPath简化路径解析)

如果需要快速解析复杂JSON路径,引入JsonPath依赖:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.8.0</version>
</dependency>

2. 定义统一处理接口

所有Category的业务逻辑都实现此接口,保证调用一致性:

public interface CategoryHandler {
    /**
     * 处理对应Category的业务逻辑
     * @param extractedValue 从JSON中解析出的目标值
     * @param originalRequest 原始请求JSON节点,便于扩展获取其他字段
     */
    void process(Object extractedValue, JsonNode originalRequest);
}

3. 实现具体Category的处理类

每个Category对应一个独立的处理Bean,例如:

// Finance类别处理器
@Component("financeHandler")
public class FinanceCategoryHandler implements CategoryHandler {
    @Override
    public void process(Object extractedValue, JsonNode originalRequest) {
        String fxType = (String) extractedValue;
        // 此处编写Finance类别专属业务逻辑
        System.out.println("处理Finance类别,获取到type值:" + fxType);
    }
}
// Retail类别处理器
@Component("retailHandler")
public class RetailCategoryHandler implements CategoryHandler {
    @Override
    public void process(Object extractedValue, JsonNode originalRequest) {
        Double value = (Double) extractedValue;
        // 此处编写Retail类别专属业务逻辑
        System.out.println("处理Retail类别,获取到value值:" + value);
    }
}

4. 配置Category映射关系

通过application.yml配置不同Category对应的JSON路径和处理Bean名称,后续新增Category只需修改配置:

category-processing:
  mappings:
    - category: Finance
      json-path: "$.history.type"
      handler-bean-name: financeHandler
    - category: Retail
      json-path: "$.history.value"
      handler-bean-name: retailHandler
    # 可继续添加其他Category配置

创建配置类绑定上述配置:

@ConfigurationProperties(prefix = "category-processing")
@Component
public class CategoryProcessingProperties {
    private List<CategoryMapping> mappings;

    // Getter & Setter
    public static class CategoryMapping {
        private String category;
        private String jsonPath;
        private String handlerBeanName;

        // Getter & Setter
    }

    public List<CategoryMapping> getMappings() {
        return mappings;
    }

    public void setMappings(List<CategoryMapping> mappings) {
        this.mappings = mappings;
    }
}

5. 实现调度器核心逻辑

调度器负责解析请求、匹配配置、调用对应处理器:

@Component
public class CategoryProcessorDispatcher {
    private final CategoryProcessingProperties properties;
    private final ApplicationContext applicationContext;
    private final ObjectMapper objectMapper;

    // 构造注入依赖
    public CategoryProcessorDispatcher(CategoryProcessingProperties properties,
                                       ApplicationContext applicationContext,
                                       ObjectMapper objectMapper) {
        this.properties = properties;
        this.applicationContext = applicationContext;
        this.objectMapper = objectMapper;
    }

    public void dispatch(String requestBody) throws IOException {
        // 解析原始请求JSON
        JsonNode rootNode = objectMapper.readTree(requestBody);
        String category = rootNode.get("marketEvent").get("category").asText();

        // 匹配当前Category的配置
        CategoryMapping mapping = properties.getMappings().stream()
                .filter(m -> m.getCategory().equals(category))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("不支持的Category:" + category));

        // 按配置的JSON路径提取目标值
        Object extractedValue = JsonPath.read(requestBody, mapping.getJsonPath());

        // 获取对应处理器并执行逻辑
        CategoryHandler handler = applicationContext.getBean(mapping.getHandlerBeanName(), CategoryHandler.class);
        handler.process(extractedValue, rootNode);
    }
}

6. 在REST接口中接入

@RestController
@RequestMapping("/market/events")
public class MarketEventController {
    private final CategoryProcessorDispatcher dispatcher;

    public MarketEventController(CategoryProcessorDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @PostMapping
    public ResponseEntity<Void> handleMarketEvent(@RequestBody String requestBody) {
        try {
            dispatcher.dispatch(requestBody);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 此处可根据实际情况返回错误信息或日志记录
            return ResponseEntity.badRequest().build();
        }
    }
}

扩展优化建议

  • 动态配置:将Category映射配置存储到数据库,配合定时任务或事件监听实现动态加载,无需重启服务
  • 缓存优化:将Category与配置的映射关系缓存到Redis或本地缓存,避免每次请求遍历配置列表
  • 异常增强:对JSON路径解析、处理器调用等环节添加异常捕获与统一处理,返回更友好的错误响应
  • 灵活取值:若需要更复杂的取值逻辑,可替换JsonPath为Spring SpEL表达式,支持自定义计算规则

内容的提问来源于stack exchange,提问作者BobCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:47:51