2013-04-16 62 views
0

我敢肯定這已被問了1000次,因爲我看過他們,但是我錯過了一些東西。Spring @Value沒有設置

上下文:

<beans profile="localDev"> 
    <util:properties id="propertiesLocalDev"location="classpath:/localDev.properties"/> 
</beans> 

<beans profile="test"> 
    <util:properties id="properties-test" location="classpath:/test.properties"/> 
</beans> 

初始化:

System.setProperty("spring.profiles.active", "localDev"); 
    GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
    ctx.load("classpath:applicationContext.xml"); 
    ctx.refresh(); 

配置:

@Configuration 
public class AppConfig { 


@Value("${test.value}") 
private String testValue; 
... 

日誌:

INFO: Loading properties file from class path resource [localDev.properties] 

屬性:

test.value=ugh 

如此看來性能越來越讀,但是不獲取設置AppConfig.testValue值。我嘗試過使用純java java/xml等等...有些配置會破壞一些工作,嘗試使用@PropertySource,但常量是testValue永遠不會被設置,所以我從根本上做錯了什麼。

總體目標是根據不同的配置文件加載不同的屬性文件。

任何人都可以看到我做錯了什麼? 謝謝

回答

0

您還需要一個PropertySourcesPlaceholderConfigurer它可以解決你的財產。這是使用配置:

<context:property-placeholder location="..." 
       local-override="true" properties-ref="propertiesLocalDev" /> 

有了這個你的財產價值應該乾淨地解決。

這也應該工作 - 使用Spring-EL:

@Value("#{@propertiesLocalDev['test.value']}") 
private String testValue; 
+0

我的理解是,取代屬性佔位符。 – Sector7B

+0

util:屬性只是創建一個屬性bean。要解析其他bean中的屬性引用,您仍然需要一個propertyplaceholder。 –

+0

剛剛嘗試過,它現在只是讀取屬性文件兩次,但仍然不起作用。 – Sector7B

0

嘗試

public class AppConfig { 

@Autowired 
private String testValue; 

} 

如果變量正確自動連接您可以使用

String sUgh = testValue.getProperty("test.value"); // = "ugh" 

我阿爾蘇會用純

<util:properties id="propertiesLocalDev"location="classpath:/localDev.properties"/> 

,而不是使用

<beans profile> 

標籤。

0

你必須使用類似,在XML只有以下

<util:properties id="test" location="classpath:fn-test-configuration.properties" /> 

現在使用,下面的方法你可以在課堂上使用的屬性值

@Value(「#{test.test.value }「)
private String testValue;

我用同樣的方式,它工作正常。

+0

我在配置文件中擁有它,因爲我想爲每個環境加載不同的屬性文件。 – Sector7B

+0

我這樣做:** ** 然後這樣:** @ Value(「#{localDev ['test.value']} 「) private String testValue; ** 沒有任何反應,但我可以在日誌中看到它讀取屬性文件。它只是沒有設定價值。 儘管如此:** @ Value(「#{localDev.test.value}」)** – Sector7B