Как сопоставить свойство класса из application.yml с классом java с другим именем класса? - PullRequest
0 голосов
/ 20 февраля 2020

Я использую Spring Framework и мне нужно сопоставить свойство class из application.yml с классом java с другим именем class ?

I иметь следующий файл 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

и мой java класс для service.cms свойств:

// 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, но я должен сохранить исходное имя webClient в application.yml. Просто использование @Value сверх CmsProperties#webClient не работает:

//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}"

Возможно ли это сделать?

Ответы [ 2 ]

3 голосов
/ 20 февраля 2020

Пожалуйста, посмотрите на подобный вопрос здесь

Так что вам не нужно @Value("${webClient}"). Просто создайте сеттер:

public void setWebClient(WebClientProperties webClient) {
    this.webClientProperties = webClient;
}
0 голосов
/ 20 февраля 2020

Да, приведенный ниже код будет работать

Класс родительского свойства

@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;
}

application.yml

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