esh*_*gle 3 annotations spring-boot
我有一个 POJO 类,它在 Spring Boot 中从 application.yaml 文件中读取属性。在这里,我需要根据主题值和另一个字符串的组合将默认值设置为 groupId(在未给出时获取)。
private String topic;
@Value("${topic}_test")
private String groupId;
Run Code Online (Sandbox Code Playgroud)
我试过这个但得到错误
无法解析值“${topic}_test”中的占位符“主题”
我创建了一个变量并尝试在 @Value 中访问它但失败了。请提供任何建议以访问此
假设您的 application.yml 文件中有这样的属性
topic: myFavoriteTopic
Run Code Online (Sandbox Code Playgroud)
groupId如果 Spring 能够使用topicapplication.yml 中的键加载属性,下面的代码会将值“myFavoriteTopic”分配给变量。如果不是,它将分配默认值“我的默认主题”。
@Value("${topic:my default topic}")
private String groupId;
Run Code Online (Sandbox Code Playgroud)
要设置null为默认值,请使用:
@Value("${topic:#{null}}")
Run Code Online (Sandbox Code Playgroud)
要使用空字符串作为默认值,请使用:
@Value("${topic:}")
Run Code Online (Sandbox Code Playgroud)
在您的代码片段中,您有一个String topic变量。对于 Spring 框架,在属性值检索中不使用此变量。当您这样做时@Value("${topic}"),“topic”是 Spring 将在 application.yml 中查找的键的名称。无法在运行时根据 Java 变量的值确定键的名称。原因是可以在类代码执行之前加载属性。
同样在您的代码片段中,您使用@Value("${topic}_test"). 在这种情况下,Spring 所做的是将“_test”连接到为属性键主题检索的值。在我的第一个示例中,groupId将分配“myFavoriteTopic_test”。
| 归档时间: |
|
| 查看次数: |
6078 次 |
| 最近记录: |