最近有朋友问@Value注入Properties数据注入不进去,接下来我就分析一下为什么。
场景:
需要注入Properties的value数据到Bean或方法参数。
准备数据:Java代码

<bean id="props" class="java.util.Properties">
<constructor-arg index="0">
<props>
<prop key="a">123</prop>
</props>
</constructor-arg>
</bean>
<bean id="map" class="java.util.HashMap">
<constructor-arg index="0">
<map>
<entry key="a" value="234"/>
</map>
</constructor-arg>
</bean>
失败的做法:Java代码

@Value ("#{props['a']}")
private String propsA;
此时无法获取props的a这个键对应的值。
正确的做法:Java代码

@Value ("#{props.getProperty('a')}")
private String propsA;
@Value ("#{map['a']}")