首页 > 解决方案 > Java:如何使用 spring 注释将 .properties 文件的内容加载到 Properties 中?

问题描述

我在 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"

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

标签: javaspring

解决方案


按如下方式注册您的属性文件

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


推荐阅读