天天看點

Spring中@value注解的使用

首先,@value需要參數,這裡參數可以是兩種形式:@Value("#{configProperties['t1.msgname']}")或者@Value("${t1.msgname}");

其次,下面我們來看看如何使用這兩形式,在配置上有什麼差別:

1、@Value("#{configProperties['t1.msgname']}")這種形式的配置中有“configProperties”,其實它指定的是配置檔案的加載對象:配置如下:

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">

        <property name="locations">

            <list>

                <value>classpath:/config/t1.properties</value>

            </list>

        </property>

    </bean>

    這樣配置就可完成對屬性的具體注入了;

    2、@Value("${t1.msgname}")這種形式不需要指定具體加載對象,這時候需要一個關鍵的對象來完成PreferencesPlaceholderConfigurer,這個對象的配置可以利用上面配置1中的配置,也可以自己直接自定配置檔案路徑。

    如果使用配置1中的配置,可以寫成如下情況:

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">

        <property name="properties" ref="configProperties"/>

    </bean>

    如果直接指定配置檔案的話,可以寫成如下情況:

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">

        <property name="location">

        <value>config/t1.properties</value>

        </property>

    </bean>