java - Spring XML+属性配置到Java类

标签 java xml spring configuration-files properties-file

我的 xml 文件中有以下配置:

<util:properties id="apiConfigurator" location="classpath:api.properties" scope="singleton"/>

这是我的属性文件:

appKey=abc
appSecret=def

在我的 Spring 类(class)中,我得到了一些像这样的值:

@Value("#{apiConfigurator['appKey']}")

我想在 Spring 中创建一个 @Configuration 类来解析属性文件,

@Value("#{apiConfigurator['appKey']}")

在我使用它的类(class)中仍然有效。我该如何正确地做到这一点?

最佳答案

当您指定时

<util:properties .../>

Spring 使用您指定的名称/id 注册一个 PropertiesFactoryBean bean。

你需要做的就是自己提供这样一个@Bean

// it's singleton by default
@Bean(name = "apiConfigurator") // this is the bean id
public PropertiesFactoryBean factoryBean() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("api.properties"));
    return bean;
}

关于java - Spring XML+属性配置到Java类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22383740/

相关文章:

java - 使用 EclipseLink 从实体生成表不会执行任何操作

android - 程序化的 android 评分栏绘制不正确

c++ - (C++) 使用天气 API

spring - DefaultMessageListenerContainer 停止处理消息

java - 如何在Spring Tool Suite 3.8.1-64中配置Eclipse Marketplace?

java - 如何知道给定字符串是否是Java中另一个字符串的子字符串

java - 使用流进行字数统计

c# - IEnumerable<XElement> 比较不一样

spring - Nginx 静态服务来自 spring boot war

java - 使用 Dagger 无法获得单例