如何在spring boot的@Value注解中读取变量或连接一个属性 [英] How to read variable or concatenate one property in @Value annotation of spring boot

查看:35
本文介绍了如何在spring boot的@Value注解中读取变量或连接一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 POJO 类,它在 Spring Boot 中从 application.yaml 文件中读取属性.这里我需要根据主题值和另一个字符串的组合将默认值设置为 groupId(未给出时获取).

I have one POJO class which read properties from application.yaml file in spring boot. Here I need to set default value to groupId(to get when not given) based on combination of topic value and another string.

private String topic;

 @Value("${topic}_test")
 private String groupId;

我试过这个但得到错误

无法解析值${topic}_test

Could not resolve placeholder 'topic' in value "${topic}_test

我创建了一个变量并尝试在@Value 中访问它但失败了.请提供访问此内容的任何建议

I create a variable and tried to access it in @Value but failed. Please provide any suggestion to access this

推荐答案

默认值

假设您的 application.yml 文件中有这样的属性

Default value

Let's say you have a property like this in your application.yml file

topic: myFavoriteTopic

如果 Spring 能够从 application.yml 加载带有键 topic 的属性,下面的代码会将值myFavoriteTopic"分配给变量 groupId.如果不是,它将分配默认值我的默认主题".

The code below will assign the value "myFavoriteTopic" to variable groupId if Spring is able to load the property with key topic from application.yml. If it's not, it will assign the default value "my default topic".

@Value("${topic:my default topic}")
private String groupId;

要将 null 设置为默认值,请使用:

To set null as the default value, use:

@Value("${topic:#{null}}")

要使用空字符串作为默认值,请使用:

To use an empty String as the default value, use:

@Value("${topic:}")

从变量中获取键名

在您的代码片段中,您有一个 String topic 变量.对于 Spring 框架,此变量在属性值检索中不使用.当您执行 @Value("${topic}") 时,topic"是 Spring 将在 application.yml 中查找的键的名称.无法在运行时根据 Java 变量的值确定键的名称.原因是可以在类代码执行之前加载属性.

Get key name from a variable

In your code snippet you have a String topic variable. For the Spring framework, this variable is not used in the property value retrieval. When you do @Value("${topic}"), "topic" is the name of the key that Spring will look for in application.yml. The name of the key cannot be determined at runtime based on the value of a Java variable. The reason is that properties can be loaded before the class code executes.

同样在您的代码片段中,您使用 @Value("${topic}_test").在这种情况下,Spring 所做的是将_test"连接到为属性键主题检索的值.在我的第一个示例中,groupId 将被分配myFavoriteTopic_test".

Also in your code snippet, you use @Value("${topic}_test"). What Spring does in this case is to concatenate "_test" to the value retrieved for property key topic. In my first example, groupId would be assigned "myFavoriteTopic_test".

这篇关于如何在spring boot的@Value注解中读取变量或连接一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆