【问题标题】:How can I interpolate a class constant in a Spring `@Value` annotation?如何在 Spring `@Value` 注释中插入类常量?
【发布时间】:2017-08-10 16:15:57
【问题描述】:

我想让 Spring 分配一个属性值。

public class Foobar {

    @Value("${example.property.foo:bar}")
    private String foo;
}

假设我想在几个不同的地方引用example.property.foo,所以我宁愿将标志分配为 Foobar 上的常量:

public class Foobar {
    public static final String FOO_PROPERTY_FLAG = "example.property.foo";
}

example.property.foo=whatever 的设置发生在别处(作为系统属性,或在 @TestPropertySource 中)。

如何在注解中引用FOO_PROPERTY_FLAG?这有效:

@Value("${" + FOO_PROPERTY_FLAG + ":bar}")

但这有点难看。我可以在这里以某种方式使用"#{}" 表达式语法吗?

@Value("${#{FOO_PROPERTY_FLAG}:bar}")  // doesn't work; value is never injected

【问题讨论】:

  • 我也有同样的问题。很想知道答案。

标签: java spring


【解决方案1】:

你可以这样做:

public static final String KEY = "propertyName";

@Value("#{T(a.b.c.package.MyConstants).KEY}")

重要的部分是指定包和类。否则 spring 将尝试在 BeanExpressionContext 中查找常量,这实际上是在执行你的 SpEL

【讨论】:

  • 这不太适合我,因为我需要注入存储在KEY 的系统属性的,而不是KEY 本身。因此我需要${} 运算符。当我尝试@Value("${#{T(a.b.c.package.MyConstants).KEY}}") 时,我收到IllegalArgumentException: could not resolve placeholder 错误。编辑了问题以澄清这一点。
  • 好的,spring 不允许使用 SpEL:Finally, while you can write a SpEL expression in @Value, such expressions are not processed from Application property files.。但是,您可以将属性加载到Properties bean 中并以某种#{myProps.getProperty(T(a.b.c.MyClass).KEY)} 访问它们。虽然丑。
  • 在我的例子中,我的值在一个键是常量的数组中。使用的数组是来自 Spring Batch 的 jobParameters。如果它可以帮助某人从这个数组中访问一个值,我已经完成了:@Value("#{jobParameters[T(a.b.c.package.MyConstants).KEY]}") private String myValue;
【解决方案2】:
private @Value("${propertyName}") String propertyField;

没有getter或setter!

通过配置加载属性:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="classpath:propertyFile.properties" name="propertiesBean"/>

还有完全非 XML 的版本:

@PropertySource("classpath:propertyFile.properties")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

确保并添加命名空间 URI xmlns:p="springframework.org/schema/p";使用 p: 前缀属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多