繁体   English   中英

如何将 application.yml 中的类属性与具有不同类名的 java 类匹配?

[英]How to match a class property from application.yml to the java class with a different class name?

我正在使用 Spring Framework 并且需要将 application.yml 中的属性匹配到具有不同名的 java 类?

我有以下 application.yml 文件:

service:
  cms:
    webClient:
      basePath: http://www.example.com
      connectionTimeoutSeconds: 3
      readTimeoutSeconds: 3
    url:
      path: /some/path/
      parameters:
        tree: basic
    credential:
      username: misha
      password: 123

和我的service.cms属性的 java 类:

// block A: It already works

@Getter
@Setter
@ConfigurationProperties(prefix = "service.cms")
public class CmsProperties {
  private WebClientProperties webClient; // I want rename it to webClientProperties
  private UrlProperties url;
  private CredentialProperties credential;
}

WebClientProperties在哪里

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class WebClientProperties {
  private String basePath;
  private int connectionTimeoutSeconds;
  private int readTimeoutSeconds;
}

我想将 java 字段名称CmsProperties#webClient重命名为CmsProperties#WebClientProperties ,但我必须在 application.yml 中保留原始名称webClient 仅在CmsProperties#webClient上使用@Value不起作用:

//Block B: `webClient` name is changed to `WebClientProperties`. 
// This what I want - but it did not work! 

@Getter
@Setter
@ConfigurationProperties(prefix = "service.cms")
public class CmsProperties {
  @Value("${webClient}")
  private WebClientProperties webClientProperties; // Name changed to `webClientProperties`
  ...
}

我有错误:

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'webClient' in value "${webClient}"

有可能做到吗?

请在这里看一个类似的问题

所以你不需要@Value("${webClient}") 只需创建一个setter:

public void setWebClient(WebClientProperties webClient) {
    this.webClientProperties = webClient;
}

是的,下面的代码将起作用

父属性类

@Configuration
@ConfigurationProperties(prefix = "service.cms")
public class PropertyReader {

    public WebClient webClient;
}


子属性类

//GETTER SETTER removed public class WebClient { @Value("${basePath}") private String basePath; @Value("${connectionTimeoutSeconds}") private String connectionTimeoutSeconds; @Value("${readTimeoutSeconds}") private String readTimeoutSeconds; }

应用程序.yml

 service: cms: webClient: basePath: http://www.example.com connectionTimeoutSeconds: 3 readTimeoutSeconds: 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM