如何为OpenAPI Generator生成的ApiClient构造器添加@Qualifier注解
如何为OpenAPI Generator生成的ApiClient构造器添加@Qualifier注解
由于OpenAPI Generator 6.2.1没有提供直接为ApiClient构造器参数添加@Qualifier的配置项,你需要通过自定义Mustache模板来实现,具体步骤如下:
1. 复制官方ApiClient模板到本地
找到OpenAPI Generator官方Java Spring模板中的apiClient.mustache文件(对应resttemplate库的模板),将其复制到你项目的自定义模板目录(比如src/main/resources/openapi-templates)。
2. 修改模板中的构造器代码
打开复制后的apiClient.mustache,找到注入RestTemplate的构造器部分,修改为以下内容,引入自定义配置变量来动态生成@Qualifier注解:
@Autowired public ApiClient({{#restTemplateQualifierName}}@Qualifier("{{restTemplateQualifierName}}") {{/restTemplateQualifierName}}RestTemplate restTemplate) { this.restTemplate = restTemplate; init(); }
这段模板逻辑是:当配置了restTemplateQualifierName参数时,自动为RestTemplate参数添加@Qualifier注解,值为配置的名称;未配置时则保持原有逻辑。
3. 生成代码时指定配置参数和模板路径
根据你使用的构建工具或CLI,添加自定义配置参数并指定模板目录:
示例:Maven插件配置
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.2.1</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>spring</generatorName> <configOptions> <!-- 指定使用resttemplate库 --> <library>resttemplate</library> <!-- 配置你需要的Qualifier名称 --> <restTemplateQualifierName>myClientProperties</restTemplateQualifierName> </configOptions> <!-- 指定自定义模板目录 --> <templateDirectory>${project.basedir}/src/main/resources/openapi-templates</templateDirectory> </configuration> </execution> </executions> </plugin>
示例:CLI命令
openapi-generator generate \ -i openapi.yaml \ -g spring \ --library resttemplate \ -c config.json \ --template-dir ./openapi-templates
其中config.json内容为:
{ "restTemplateQualifierName": "myClientProperties" }
4. 验证生成结果
执行代码生成命令后,检查生成的ApiClient.java,构造器会自动带上指定的@Qualifier注解:
@Autowired public ApiClient(@Qualifier("myClientProperties") RestTemplate restTemplate) { this.restTemplate = restTemplate; init(); }
这种方式无需修改现有RestTemplate Bean的定义,也不用标记@Primary,完美适配多RestTemplate Bean的场景。
内容的提问来源于stack exchange,提问作者MaexNi
相关产品推荐
相关产品推荐

