我如何访问使用 spring 中的 applicationcontext.xml 文件归档的属性文件?

how can i access properties file filed using applicationcontext.xml file in spring?

我在我的 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 class 中写了以下行来访问此文件

         @Value("${spring.username}")
         private String usr;

但我得到的 usr 价值就像 =${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 属性