[英]Builder pattern with spring boot @component annotated class
I am a newbie with spring.我是春天的新手。 I am trying to build a URL using the properties from application.properties file in a spring boot project using the org.springframework.beans.factory.annotation.Value
annotation.我正在尝试使用org.springframework.beans.factory.annotation.Value
注释在 Spring Boot 项目中使用 application.properties 文件中的属性构建一个 URL。
The class ElasticConfiguration picks the properties from the property file. ElasticConfiguration 类从属性文件中选取属性。 But, there can be scenarios where the port and protocol are optional.但是,可能存在端口和协议是可选的情况。
@Component
public class ElasticConfiguration {
@Value("${elasticsearch.hostname}")
String hostname;
@Value("${elasticsearch.portnumber}")
Integer portnumber;
@Value("${elasticsearch.protocol}")
String protocol;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPortnumber() {
return portnumber;
}
public void setPortnumber(Integer portnumber) {
this.portnumber = portnumber;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
}
To solve it i am using a builder class which builds the URL object basing on the available properties为了解决这个问题,我使用了一个构建器类,它根据可用属性构建 URL 对象
public class URL {
private final String _hostname;
private final String _portnumber;
private final String _protocol;
private URL(URLBuilder builder){
this._hostname = builder._hostname;
this._portnumber = builder._portnumber;
this._protocol = builder._protocol;
}
public String get_hostname() {
return _hostname;
}
public String get_portnumber() {
return _portnumber;
}
public String get_protocol() {
return _protocol;
}
public static class URLBuilder {
private final String _hostname;
private String _portnumber;
private String _protocol;
public URLBuilder(String hostname){
this._hostname = hostname;
}
public URLBuilder portNumber(String value) {
this._portnumber = value;
return this;
}
public URLBuilder protocol(String value) {
this._protocol = value;
return this;
}
public URL build() {
return new URL(this);
}
}
@Override
public String toString() {
return "URL [_hostname=" + _hostname + ", _portnumber=" + _portnumber + ", _protocol=" + _protocol + "]";
}
}
I would like to use a builder approach in the spring boot @component
annotated class.我想在 spring boot @component
注释类中使用构建器方法。
使用 lombok.jar,它会有@builder 来解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.