本文介绍了如何将application.yml中的类属性与具有不同类名的java类进行匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Framework,并且需要将application.yml中的 class 属性与具有不同 class 名称的Java类进行匹配?

I am using Spring Framework and need to match a class property from application.yml to the java class with a different class name?

我有以下application.yml文件:

I have the following application.yml file:

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类:

and my java class for service.cms properties:

// 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不起作用:

I would like to rename java field name CmsProperties#webClient into CmsProperties#WebClientProperties, but I must keep the original name webClient in the application.yml.Just using @Value over CmsProperties#webClient does not work:

//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:

So you don't need @Value("${webClient}"). Just create a setter:

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

这篇关于如何将application.yml中的类属性与具有不同类名的java类进行匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:23