當在Spring ApplicationContext中使用屬性文件時,可以通過以下方式訪問其屬性:$ {someproperty}在xml配置文件中。但是,如何在不通過xml注入的情況下訪問java代碼中的相同屬性?如何通過ApplicationContext訪問屬性
的ApplicationContext配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="myapp.properties" />
</bean>
<bean class="my.app.MyClass">
<property name="foo" value="${someproperty}" />
</bean>
</beans>
屬性
someproperty=somevalue
更新1
這樣做的實際點,就是對應用程序的唯一ID是一個特例在屬性文件中設置(由系統管理員編輯)。有幾個應用程序類實現了ApplicationContextAware,因此它們可以訪問上下文並防止在每個類中注入或爲每個我們想要一個ez屬性訪問方法的類定義一個bean。我們的應用程序「瞭解」Spring在這種情況下不是問題。
你能解釋一下「防止在每個班級注射或爲每個班級定義一個bean」嗎? – kan
如果我們不使用註釋,那麼對於每個需要訪問屬性本身的bean,都應該使用「property」標籤。它只是將工作從類移動到xml。 –
我實際上傾向於使用類似於此博客文章中的配置類:http://chrislovecnm.com/2010/03/08/spring-3-java-based-configuration-with-value/ –