[轉]Spring通過@Value注解注入屬性的幾種方式


原文地址:https://blog.csdn.net/csujiangyu/article/details/50945486

-------------------------------------------------------------

場景
假如有以下屬性文件dev.properties, 需要注入下面的tag

tag=123

通過PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
代碼

@Value("${tag}")
private String tag;
通過PreferencesPlaceholderConfigurer
<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
代碼:

@Value("${tag}")
private String tag;
通過PropertiesFactoryBean
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="dev.properties" />
</bean>
代碼:

@Value("#{config['tag']}")
private String tag;
通過util:properties
效果同PropertiesFactoryBean一樣

代碼:

@Value("#{config['tag']}")
private String tag;
其他方式
有時也可以不通過文件,直接寫字面量

<bean id="appConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--<property name="location" value="classpath:${env}.properties" />-->
<property name="properties">
<props>
<prop key="tag">123</prop>
</props>
</property>
</bean>
代碼:

@Value("${tag}")
private String tag;
---------------------
作者:Ydoing
來源:CSDN
原文:https://blog.csdn.net/csujiangyu/article/details/50945486?utm_source=copy
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM