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

Swagger Codegen对定义中必填字段的强制执行问题

解决Swagger Codegen生成Spring类时必填字段不生效的问题

我懂你的困扰——你已经在Swagger YAML规范里把MyType的name和amount标记为必填项,但用Swagger Codegen Maven插件(2.2.3版本,指定spring语言和spring-mvc库)生成Java类后,这些字段并没有被设置为必填(比如没加上@NotNull这类验证注解)。下面是具体的解决步骤:

1. 添加插件配置开启验证注解生成

Swagger Codegen 2.x版本默认不会自动生成验证注解,你需要在插件配置里添加additionalProperties参数来开启这个功能,指定使用JSR-380(javax.validation)的注解。

修改你的Maven插件配置如下:

<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.3</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <language>spring</language>
                <library>spring-mvc</library>
                <!-- 开启验证注解生成 -->
                <additionalProperties>
                    <property>
                        <name>javax.validation.annotations</name>
                        <value>true</value>
                    </property>
                    <!-- 可选:确保使用Bean Validation注解 -->
                    <property>
                        <name>useBeanValidation</name>
                        <value>true</value>
                    </property>
                </additionalProperties>
                <!-- 配置Swagger规范文件路径和生成代码输出目录 -->
                <inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec>
                <output>${project.build.directory}/generated-sources/swagger</output>
            </configuration>
        </execution>
    </executions>
</plugin>

2. 确认Swagger YAML的必填配置无误

先确保你的MyType定义没有语法问题,你现有的配置是正确的,再核对一下:

MyType:
  type: object
  required:
    - name
    - amount
  properties:
    name:
      type: string
    amount:
      type: number
      format: double # 根据你的实际需求调整数值类型

3. 验证生成的类

执行mvn clean generate-sources命令重新生成代码,之后查看生成的MyType类,应该会看到类似这样的代码:

import javax.validation.constraints.NotNull;

public class MyType {
    @NotNull
    private String name;

    @NotNull
    private Double amount;

    // 对应的getter和setter方法
}

额外提示

  • 如果你用的是Spring Boot 2.x及以上版本,需要引入spring-boot-starter-validation依赖,才能让这些验证注解在运行时生效:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
  • 注意Swagger Codegen 2.2.3是比较旧的版本,如果后续有升级计划,3.x版本的插件(groupId为io.swagger.codegen.v3的swagger-codegen-maven-plugin)对验证注解的支持更完善,但上述配置在2.2.3版本中是完全有效的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:43:10