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?
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;
}
Yes, below code will work
Parent Property class
@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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.