我是春天的新手。我正在尝试使用org.springframework.beans.factory.annotation.Value
注释在spring启动项目中使用application.properties文件中的属性构建URL。
ElasticConfiguration类从属性文件中选取属性。但是,可能存在端口和协议是可选的情况。
@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;
}
}
要解决这个问题,我正在使用一个构建器类,它基于可用的属性构建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 + "]";
}
}
我想在spring boot @component
注释类中使用构建器方法。
答案 0 :(得分:0)
使用 lombok.jar,它会有@builder 来解决你的问题