java - 如何在 Spring 中使用 applicationcontext.xml 文件访问属性文件字段?

标签 java spring maven applicationcontext

我在我的 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/

相关文章:

java - 如何将 Maven 添加到 IntelliJ 中现有的 Java Web 应用程序?

java - 混合和受限元素无法通过 Xmlbeans 进行验证

java - 页面未在所需的框架中加载

java - 设置springboot启动检查redis,database,mq

maven - 为什么使用 Maven 版本插件(版本 :use-latest-versions) not updating/changing -SNAPSHOT version to release (none -SNAPSHOT version)?

java - Maven 未下载库(netbeans)

java - 如何将方法签名从一个类复制到一个文件?

java - 如何从 Retrofit2 拦截器开始登录 Activity

java - Spring JUnit 和 Mockito - SimpleJdbcTemplate

Spring MVC bean映射到HTTP GET请求参数类似于@BeanParam