我在我的 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;
但我得到的 usr 的值(value)就像 =${spring.username} 我在这里缺少什么?
最佳答案
@Value("${spring.username}") 表示法需要根据 Spring 版本使用 PropertyPalceholderConfigurer/PropertySourcesPlaceholderConfigurer 来解析属性占位符。要么
解决方案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 属性
关于java - 如何在 Spring 中使用 applicationcontext.xml 文件访问属性文件字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053784/