我正在使用Spring Framework,需要将application.yml中的class属性与具有不同class名称的java类进行匹配?
我有以下应用程序.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
。仅仅使用@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}"
有可能做到吗?
请看一下这里的类似问题
所以你不需要@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;
}
application.yml
service:
cms:
webClient:
basePath: http://www.example.com
connectionTimeoutSeconds: 3
readTimeoutSeconds: 3