gpt4 book ai didi

java - 具有嵌套条件的 SpEL @Value

转载 作者:行者123 更新时间:2023-12-01 19:30:06 25 4
gpt4 key购买 nike

我正在使用@Value注释,并且我希望它现在变得更复杂一些。我有两个配置值 - val1val2。我想按如下方式注入(inject)它:如果配置中存在 val1 ,则使用它。否则,如果 val2 为 true,则注入(inject) default1。如果为 false,则注入(inject) default2

我尝试过类似的方法:

@Value("#{val1 ? val1 : (val2 ? 'default1' : 'default2')}")

但我不断得到:

`EL1008E`: property or filed 'val1' cannot be found on object of type 'org.springframeowrk.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

当我尝试其他表达式时,例如 ${val1}'${val1}' 它似乎仍然不起作用。

@Value 注释中执行嵌套条件的正确方法是什么,还是太复杂?

最佳答案

我调整了表达式并编写了一个小测试来说明变化。简而言之,使用 ${some.prop:defaultVal} 定义默认值,使用 ${some.prop:} 定义空字符串作为默认值。另外,在 SPEL 表达式中使用单引号 ' 来指示字符串值而不是引用。

使用TestPropertySource来验证结果。我添加了第二个测试来表明,当默认值不存在时,Spring 可能(并非总是)决定返回占位符的文本表示形式。


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"val1=v1", "val2=v2"})
public class SomeTest {

@Value("#{ '${val1:}' != '' ? '${val1}' : ('${val2:}' != '' ? 'default1' : 'default2')}")
private String testVal;

@Value("${nonExistingValue}")
private String nonExistingValue;

@Test
public void test() {
assertThat(testVal).isEqualTo("v1");
}

@Test
public void testNonExistingValue() {
assertThat(nonExistingValue).isEqualTo("${nonExistingValue}");
}
}

虽然上面的表达式有效,但我强烈建议使用 ConfigurationProperties ,或 T expression type operator引用静态方法。当表达式变得更加复杂时,当前设置的可读性可能会变得更差。

关于java - 具有嵌套条件的 SpEL @Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com