如何使用带有@Value 注释的字符串来连接其他字符串?
how to use strings which annotation with @Value in order to join the other strings?
我想使用带有注释@Value 的字符串,但如果我尝试将它们连接到另一个字符串,它们会变成空 object.If 我只使用它们,它们有效 well.What 我需要使用他们加入另一个字符串或这些字符串不能加入其他字符串?
@Value("${Example.com}")
private String HOST_NAME;
private String BASE_URL="http://"+HOST_NAME+":8080";
System.out.println(HOST_NAME);
// Output is 123.123.123.1123;(For example)
System.out.println(BASE_URL);
// Output like that http://null:8080;
此处:
private String BASE_URL="http://"+HOST_NAME+":8080";
HOST_NAME
是 null
因为在 Java 中,字段初始值设定项在 class 构造函数之前求值,但在 Spring 启动时,Spring 使用 @Value
注释的值字段,例如:
@Value("${Example.com}")
private String HOST_NAME;
仅在调用构造函数之后。
所以为了解决你的要求,在构造函数中设置BASE_URL
例如:
private String BASE_URL;
public FooClass(){
BASE_URL="http://"+HOST_NAME+":8080";
}
不是你的问题,但你可以使用 @Value
的构造函数注入。它使 class 更少 Spring 依赖并且更易于单元测试。
private String BASE_URL;
private String HOST_NAME;
public FooClass(@Value("${Example.com}") String hostName){
this.HOST_NAME = hostName;
this.BASE_URL="http://"+HOST_NAME+":8080";
}
它不会工作,因为 sprint 在对象构造之后初始化属性。
此问题的解决方案可能是在您的属性中存储整个模式:
hostname=example.com
port=8080
base-url=http://${hostname}:${port}
使用base-url
:
@Value("${base-url}")
private String baseUrl;
// ...
System.out.println(baseUrl); // Will print http://example.com:8080
您得到 BASE_URL="http://null:8080";
的问题,因为字段初始值设定项是在创建 bean 之后计算的。
我遇到了类似的问题,我想到了这个:
@Value("http://${Example.com}:8080")
private String HOST_NAME;
Now your HOST_NAME
will have the value : http://whatever.com:8080
我想使用带有注释@Value 的字符串,但如果我尝试将它们连接到另一个字符串,它们会变成空 object.If 我只使用它们,它们有效 well.What 我需要使用他们加入另一个字符串或这些字符串不能加入其他字符串?
@Value("${Example.com}")
private String HOST_NAME;
private String BASE_URL="http://"+HOST_NAME+":8080";
System.out.println(HOST_NAME);
// Output is 123.123.123.1123;(For example)
System.out.println(BASE_URL);
// Output like that http://null:8080;
此处:
private String BASE_URL="http://"+HOST_NAME+":8080";
HOST_NAME
是 null
因为在 Java 中,字段初始值设定项在 class 构造函数之前求值,但在 Spring 启动时,Spring 使用 @Value
注释的值字段,例如:
@Value("${Example.com}")
private String HOST_NAME;
仅在调用构造函数之后。
所以为了解决你的要求,在构造函数中设置BASE_URL
例如:
private String BASE_URL;
public FooClass(){
BASE_URL="http://"+HOST_NAME+":8080";
}
不是你的问题,但你可以使用 @Value
的构造函数注入。它使 class 更少 Spring 依赖并且更易于单元测试。
private String BASE_URL;
private String HOST_NAME;
public FooClass(@Value("${Example.com}") String hostName){
this.HOST_NAME = hostName;
this.BASE_URL="http://"+HOST_NAME+":8080";
}
它不会工作,因为 sprint 在对象构造之后初始化属性。
此问题的解决方案可能是在您的属性中存储整个模式:
hostname=example.com
port=8080
base-url=http://${hostname}:${port}
使用base-url
:
@Value("${base-url}")
private String baseUrl;
// ...
System.out.println(baseUrl); // Will print http://example.com:8080
您得到 BASE_URL="http://null:8080";
的问题,因为字段初始值设定项是在创建 bean 之后计算的。
我遇到了类似的问题,我想到了这个:
@Value("http://${Example.com}:8080")
private String HOST_NAME;
Now your
HOST_NAME
will have the value : http://whatever.com:8080