【问题标题】:OpenAPI generator add/generate annotation to ApiClient constructorOpenAPI 生成器向 ApiClient 构造函数添加/生成注释
【发布时间】:2023-01-12 18:51:38
【问题描述】:

我使用最新的 OpenAPI 生成器 6.2.1 (https://github.com/OpenAPITools/openapi-generator) 生成带有 resttemplate 库的 ApiClient,效果很好。

在我的应用程序中,我现在有两个不同的 RestTemplate bean。所以 Spring 不知道在 ApiClient 构造函数中使用哪一个。

com.xyz.ApiClient 中构造函数的参数 0 需要一个 bean,但找到了 2 个

还有解决问题的提示:

考虑将其中一个 bean 标记为 @Primary,更新消费者以接受多个 bean,或者使用 @Qualifier 来标识应该被消费的 bean

我不想用 @Primary 标记其中一个 bean,因为它不是要使用的主 bean。

我想将 @Qualifier 添加到生成的 ApiClient 构造函数中,如下所示:

    @Autowired
    public ApiClient(@Qualifier("myClientProperties") RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        init();
    }

如何将 @Qualifier 注释添加到生成的构造函数?

我阅读了很多 openapi 生成器文档,但没有找到任何有用的信息。有一个为模型添加注释的解决方案(OpenApi 配置的 configOptions 中的 additionalModelTypeAnnotations)。

我希望为 ApiClient 构造函数生成一个 @Qualifier 注释。

【问题讨论】:

    标签: spring annotations openapi resttemplate openapi-generator


    【解决方案1】:

    您可以为生成的类禁用组件扫描。假设您的根包是“my.root.package”并且您将类生成到“my.root.package.generated”中,使用以下注释您的 App / Config 类:

    @ComponentScan(basePackages = "my.root.package",
               excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX,
                                                      pattern = "my.root.package.generated.*"))
    

    然后,您可以根据您的其余模板创建自己的(合格的)ApiClients:

    @Bean("rest-template-1")
    public RestTemplate restTemplate1() {
        return new RestTemplate();
    }
    
    @Bean("rest-template-2")
    public RestTemplate restTemplate2() {
        return new RestTemplate();
    }
    
    @Bean("api-client-1")
    public ApiClient apiClient1(@Qualifier("rest-template-1") RestTemplate restTemplate) {
        return new ApiClient(restTemplate);
    }
    
    @Bean("api-client-2")
    public ApiClient apiClient2(@Qualifier("rest-template-2") RestTemplate restTemplate) {
        return new ApiClient(restTemplate);
    }
    

    使用这些不同的合格 ApiClient,您可以根据需要初始化 API 类。

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2022-06-21
      相关资源
      最近更新 更多