【问题标题】:Spring XML + properties configuration to Java ClassSpring XML + 属性配置到 Java 类
【发布时间】:2014-04-18 11:44:42
【问题描述】:

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

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

这是我的属性文件:

appKey=abc
appSecret=def

在我的春季课程中,我得到了一些像这样的值:

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

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

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

仍然可以在我使用它的课程中进行彻底的工作。我该如何正确地做到这一点?

【问题讨论】:

  • 试试this
  • 它看起来很接近,但它没有说明任何关于给配置集一个 id,并使其以我需要的“类似哈希”的方式访问:apiConfigurator['foo']

标签: java xml spring configuration-files properties-file


【解决方案1】:

当你指定时

<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;
}

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2017-06-21
    • 2012-10-19
    • 1970-01-01
    • 2011-08-31
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多