Details several ways that Spring can inject properties through the @Value annotation
- 2020-06-15 09:12:02
- OfStack
scenario
If you have the following properties file dev.properties, inject the following tag
tag=123
Through PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
code
@Value("${tag}")
private String tag;
Through PreferencesPlaceholderConfigurer
<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
Code:
@Value("${tag}")
private String tag;
Through PropertiesFactoryBean
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="dev.properties" />
</bean>
Code:
@Value("#{config['tag']}")
private String tag;
Through util: properties
The effect is the same as PropertiesFactoryBean1
Code:
@Value("#{config['tag']}")
private String tag;
The other way
Sometimes it is possible to write directly without using a document
<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>
Code:
@Value("${tag}")
private String tag;