【问题标题】:Java : How to load content of .properties file into Properties using spring annotation?Java:如何使用 spring 注释将 .properties 文件的内容加载到 Properties 中?
【发布时间】:2019-03-14 22:00:41
【问题描述】:

我在 Spring 框架上使用 Java 8。我有一个属性文件,其中包含“=”分隔值。我正在尝试使用 spring 注释直接将属性文件的值加载到属性中。 例如 : 我的 Application.properites 有:

cat=250
dog=560
lama=1000
donkey=650

我已经在我的 context.xml 中声明了这个属性文件:

<util:properties id="app_props"
                 location="classpath*:/application.properties" />

现在在我的主类中,我试图将 Application.properites 中的所有值加载到

private Properties properties;

这样 properties.getProperty("cat") 将返回 "250"

不知道该怎么做。我可以得到任何帮助吗?

【问题讨论】:

  • 这是一个新项目还是旧项目的更新?
  • 你试过用@Resource(name="app_props")注释properties吗? util:properties 不是初始化/加载“属性”的正确方法;我建议您查看context:property-placeholder,然后使用Environment@Value

标签: java spring


【解决方案1】:

如下注册你的属性文件

XML 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

      <context:property-placeholder location="classpath:foo.properties" />

</beans> 

Java 配置

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
    //...
}

如下使用你的属性

@Value( "${jdbc.url}" )
private String jdbcUrl;

您可以在我的 GitHub 存储库中找到完整的工作解决方案

https://github.com/mirmdasif/springmvc/tree/master/springproperties

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 2021-08-05
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
相关资源
最近更新 更多