【问题标题】:How to inject a keyvalue properties file with Spring?如何使用 Spring 注入键值属性文件?
【发布时间】:2014-09-09 07:59:50
【问题描述】:

我有一个键值属性文件,其中包含错误代码及其错误消息。

我想在应用程序启动时注入这个文件,这样我就可以在不需要读取文件的情况下查找注入的属性。

以下只是伪代码,Spring 中是否有任何可以创建此设置的内容?

@Value(location = "classpath:app.properties")
private Properties props;

而 app.properties 包含:

error1=test
error2=bla
...

如果没有,没有弹簧我怎么能做到这一点?

【问题讨论】:

  • 你可以在春天用resourceBundle 做到这一点

标签: java spring properties io


【解决方案1】:

感谢“kocko”的帮助,以下设置按预期工作,只有注释配置:

@Bean(name = "errors")
public PropertiesFactoryBean mapper() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("errors.properties"));
    return bean;
}

@Resource(name = "errors")
private Properties errors;

或者如果资源不应该作为 bean 提供,而只是在 @Component 中加载:

@Component
public class MyLoader {
    private Properties keys;

    @PostConstruct
    public void init() throws IOException {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new ClassPathResource("app.properties"));
        bean.afterPropertiesSet();
        keys = bean.getObject();
    }
}

【讨论】:

  • +1。好的!其实挺简单的,只是我太困了,没想到这个办法。
【解决方案2】:

@M 萨赫 您也可以使用属性位置而不是位置,因此您不必使用列表

【讨论】:

    【解决方案3】:

    我在我的项目中这样做

      <bean id="myPropertyHolder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
          <list>
             <value>classpath:myApplication.properties</value> 
          </list>
        </property>
      </bean>
    

    然后使用下面的属性

    <property name="testProperty" value="${testProperty}" />
    

    【讨论】:

      【解决方案4】:

      您可以首先在 Spring 配置中使用 &lt;util:properties&gt; 声明属性文件:

      <util:properties id="messages" location="classpath:app.properties" />
      

      这会注册一个名为 messages 的 bean,您可以在其他 bean 中自动装配/注入。

      @Autowired
      @Qualifier("messages")
      private Properties props;
      

      更多信息:

      【讨论】:

      • 没有xml配置可以吗? (我有并且喜欢只坚持基于注释的配置)
      • 我想是的,是的。看看这个:stackoverflow.com/questions/7219097/…
      • 坚持基于注释的配置很酷,它允许您最小化 xml 配置,而不是摆脱它:)
      • 我也想这样做,只是以编程方式。
      猜你喜欢
      • 1970-01-01
      • 2017-03-18
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 2010-09-23
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多