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

使用Swagger Codegen Spring生成器能否集成Spring Rest转换器?

解决方案:Spring生成器结合自定义配置+Spring转换器

1. 让OpenAPI Codegen直接使用java.util.Locale

在你的OpenAPI规范(yaml/json)中,给对应参数添加x-java-type扩展字段,指定映射到原生java.util.Locale,避免生成冗余Dto:

paths:
  /your-api-path:
    get:
      parameters:
        - name: locale
          in: body
          required: true
          schema:
            type: string
            x-java-type: java.util.Locale

2. 配置Spring转换器自动处理Locale序列化/反序列化

方式一:自定义字符串转Locale的转换器

创建转换器并注册到Spring上下文,处理zh-CN、en_US这类格式的字符串:

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.Locale;

@Component
public class StringToLocaleConverter implements Converter<String, Locale> {
    @Override
    public Locale convert(String source) {
        // 兼容下划线和短横线分隔的格式
        return Locale.forLanguageTag(source.replace("_", "-"));
    }
}

方式二:配置Jackson支持Locale(JSON参数场景)

如果接口接收JSON格式参数,可通过Jackson配置自定义Locale的序列化规则:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Locale;

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        // 自定义Locale序列化/反序列化逻辑
        module.addSerializer(Locale.class, new com.fasterxml.jackson.databind.ser.std.ToStringSerializer());
        module.addDeserializer(Locale.class, new com.fasterxml.jackson.databind.deser.std.StringDeserializer());
        mapper.registerModule(module);
        return mapper;
    }
}

3. Maven插件生成配置示例

确保插件启用spring生成器,同时开启接口仅生成模式(按需调整):

<plugin>
    <groupId>io.swagger.codegen.v3</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>3.0.34</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
                <generatorName>spring</generatorName>
                <configOptions>
                    <interfaceOnly>true</interfaceOnly>
                    <java8>true</java8>
                    <useSpringBoot3>true</useSpringBoot3>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

最终生成的接口会和你之前的简洁写法一致:

@GetMapping
public String yourMethodName(@RequestBody Locale locale);

Spring会自动完成参数转换,无需手动调用LocaleUtils.from()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:45:37