我在applicationContext文件中添加了以下内容
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:stage.properties</value>
<value>classpath:environment.properties</value>
</list>
</property>
</bean>
我需要访问stage.properties文件值.stage.properties文件位于src / main / resources
我在我的java类中编写了以下行来访问此文件
@Value("${spring.username}")
private String usr;
但我得到的价值就像= $ {spring.username} 我在这里缺少什么?
答案 0 :(得分:1)
@Value(“$ {spring.username}”)表示法需要使用PropertyPalceholderConfigurer / PropertySourcesPlaceholderConfigurer,具体取决于Spring版本来解析属性占位符。
解决方案1
替换
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:stage.properties</value>
<value>classpath:environment.properties</value>
</list>
</property>
</bean>
与
<context:property-placeholder location="classpath:stage.propertes,classpath:environment.properties"/>
确保导入Spring上下文命名空间
解决方案2.
使用SpEL使用@Value访问属性bean,如下所示
@Value("#{properties['spring.username']}
private String usr;
这将访问上下文中属性bean的spring.username属性