![](/img/trans.png)
[英]Is it possible to parse a property from application.yml to the java class field with a different name?
[英]How to match a class property from application.yml to the java class with a different class name?
我正在使用 Spring Framework 并且需要将 application.yml 中的类属性匹配到具有不同类名的 java 类?
我有以下 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
和我的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
。 仅在CmsProperties#webClient
上使用@Value
不起作用:
//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}"
有可能做到吗?
是的,下面的代码将起作用
父属性类
@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; }
应用程序.yml
service: cms: webClient: basePath: http://www.example.com connectionTimeoutSeconds: 3 readTimeoutSeconds: 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.