java - 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"
不知道该怎么做。我可以得到任何帮助吗?
解决方案
按如下方式注册您的属性文件
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
推荐阅读
- java - 我在这里缺少什么或者我应该做不同的事情?
- android - Sinch 应用程序到应用程序的语音通话不起作用
- django - Django elasticsearch dsl没有识别我创建的索引
- c# - Application.Run() 破坏其他功能
- c++ - CPP:string.find()==0 和 string.find !=string::npos 之间的区别
- logging - 使用单个 awk 命令将日期格式从文本更改为数字
- c# - 如何在没有 IDE 的情况下在我的源代码文件 .cs 中使用包?
- vb.net - 从 vb.net 中的剪贴板读取一行不匹配的文本
- python - ModuleNotFoundError:没有名为“yaml”的模块错误
- java - 自签名证书与 CA