java - 在 YML 中的接口(interface)列表中设置类

标签 java spring-boot yaml

我有一个有 2 个实现的接口(interface)。我需要在配置文件中明确设置我将使用的实现。目前,我在启动 Spring Boot 应用程序时收到错误“原因:元素 [api.services[0].esrigeolocationfinderserviceimpl,api.services[1].peliasgeolocationfinderserviceimpl] 未绑定(bind)”。以下是类(class):

public interface MyService {
   // Some methods here
}

 @Data
 @Component
 @NoArgsConstructor
 public class MyFirstServiceImpl implements MyService {

     private String first;
 }

 @Data
 @Component
 @NoArgsConstructor
 public class MySecondServiceImpl implements MyService {
   private String second;
 }

 @Data
 @Configuration
 @EnableConfigurationProperties
 @ConfigurationProperties(prefix="api")
 public class MyConfig {
     @Autowired
     private List<MyService> services;
 }

application.yml:

 api:
  services[0]: { first: aValue }
  services[1]: { second: anotherValue }

你知道我们如何设置接口(interface)列表中的值吗?

谢谢

最佳答案

您可以通过在 @Component 类中使用注释来实现此目的 @PropertySource("classpath:api.services[0]")

看看这里:Configuration properties in spring boot

关于java - 在 YML 中的接口(interface)列表中设置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58199440/

相关文章:

java - SnakeYAML正在实例化ArrayList而不是HashMap

YAML:将内联与同一对象的常规 map 混合

java - 到达数组中的最后一个索引后返回第一个索引

java - Android XML RSA,错误 : java. security.InvalidKeyException:传递给 RSA 的未知 key 类型

java - 在 catch 子句中,当我没有创建任何异常时,如何记录异常实例

java - : Unable to start web server; nested exception is org. springframework.boot.web.server.WebServerException:无法启动嵌入式Tomcat

java - Bufferedreader 关闭后,Inputstream 也应该关闭吗?

spring-boot - OpenAPI 生成器 maven 插件

java - 如何使用 Springboot 在 REST 请求 URL 中将 json 对象作为参数传递

此上下文中不允许 YAML 映射值