Java 如何在Spring`@Value`注释中插入类常量?
我想让Spring指定一个属性值Java 如何在Spring`@Value`注释中插入类常量?,java,spring,Java,Spring,我想让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.
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=其他地方发生的任何事情(作为系统属性,或在@TestPropertySource
中)
如何在注释中引用FOO\u PROPERTY\u FLAG
?这项工作:
@Value("${" + FOO_PROPERTY_FLAG + ":bar}")
但这有点难看。我可以在这里使用“#{}”
表达式语法吗
@Value("${#{FOO_PROPERTY_FLAG}:bar}") // doesn't work; value is never injected
没有能手或二传手
通过配置加载属性时:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:propertyFile.properties" name="propertiesBean"/>
确保并添加命名空间URIxmlns:p=“springframework.org/schema/p”
;要使用前缀属性,可以执行以下操作:
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:无法解析占位符
错误。编辑该问题以澄清这一点。好的,spring不允许使用SpEL来实现这一点:最后,虽然您可以在@Value中编写SpEL表达式,但这些表达式不会从应用程序属性文件中处理。
。但是,您可以将属性加载到properties
bean中,并以某种{myProps.getProperty(T(a.b.c.MyClass.KEY)}
访问它们。但是很难看。在我的例子中,我的值在一个数组中,其中键是常量。使用的数组是Spring批处理中的jobParameters。如果它能帮助某人从这个数组中访问一个值,我已经做了:@value(#{jobParameters[T(a.b.c.package.MyConstants.KEY]}”)私有字符串myValue代码>
@PropertySource("classpath:propertyFile.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public static final String KEY = "propertyName";
@Value("#{T(a.b.c.package.MyConstants).KEY}")