Mikhail Geyer
Mikhail Geyer

Reputation: 1171

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

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

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

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

where WebClientProperties is

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

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`
  ...
}

I have errors:

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

Is it possible to do it?

Upvotes: 0

Views: 2691

Answers (2)

Dmitrii Bocharov
Dmitrii Bocharov

Reputation: 935

Please, take a look at a similar question here

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

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

Upvotes: 3

Swarit Agarwal
Swarit Agarwal

Reputation: 2648

Yes, below code will work

Parent Property class

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

    public WebClient webClient;
}


Child Property Class

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

Upvotes: -1

Related Questions