2017-08-10 48 views
1

我想讓Spring分配一個屬性值。如何在Spring`@ Value`註釋中插入一個類常量?

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 
+0

我有同樣的問題。好奇看到答案。 – dFrancisco

回答

0
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:前綴屬性

1

你可以這樣做:

public static final String KEY = "propertyName"; 

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

的重要組成部分,是指定的包和類。否則,spring會嘗試在BeanExpressionContext中查找常量,它實際上正在執行您的SpEL

+0

這對我來說不太合適,因爲我需要注入存儲在KEY中的系統屬性的**值**,而不是'KEY'本身。因此我需要'$ {}'操作符。當我嘗試'@Value(「$ {#{T(a.b.c.package.MyConstants).KEY}}」)',我得到一個'IllegalArgumentException:無法解析佔位符錯誤。編輯這個問題來澄清這一點。 – Sasgorilla

+0

好的,spring不允許使用SpEL來做到這點:'最後,雖然你可以在@Value中編寫一個SpEL表達式,但這些表達式不會從應用程序屬性文件中處理。然而你可以將屬性加載到'Properties' bean中,並通過某種'#{myProps.getProperty(T(a.b.c.MyClass).KEY)}'來訪問它們。雖然很醜。 –