本文參考自: https://blog.csdn.net/ryelqy/article/details/77453713
@Value能讓我們在java代碼中使用property文件的屬性,使用@Value有兩種形式:
1、@Value("#{configProperties['t1.msgname']}")
2、@Value("${t1.msgname}")
這兩種形式,最大的區別在於配置:
1、
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:/config/t1.properties</value> </list> </property> </bean>
備注:configProperties是此bean的id,可自定義,並不是說一定得是configProperties
PropertiesFactoryBean 加載Properties文件的工廠類
2、@Value("${t1.msgname}")的配置既可以在1的基礎上擴展,也能完全自己配置
擴展方式:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> //1中bean的id </bean>
備注:核心是PreferencePlaceholderConfigurer 可以理解為最優先的選擇
自己配置:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="location"> <value>config/t1.properties</value> </property> </bean>
------------------------------------------------------
前提:
1、當前類使用@Component或由@Component擴展開來的注解,
2、xml文件內配置了是通過pakage掃描包
<context:component-scan base-package="pakage_name"/>
-------------------------------------------------------
spring boot中使用
spring boot中,我們只需要在application.properties中添加屬性即可使用,spring boot已配置好上述一切