简体   繁体   English

Java:如何使用Spring注释将.properties文件的内容加载到Properties中?

[英]Java : How to load content of .properties file into Properties using spring annotation?

I am using Java 8 on spring framework. 我在spring框架上使用Java 8。 I have a properties file which has "=" separated values in it. 我有一个属性文件,其中包含“ =”分隔的值。 I am trying to load the values of the properties file into a Property directly using spring annotation. 我试图直接使用spring注释将属性文件的值加载到Property中。 For example : my Application.properites has: 例如:我的Application.properites具有:

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

And I have declared this properties file in my context.xml as : 我在context.xml中将此属性文件声明为:

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

Now in my main class I am trying to load all of the values in Application.properites into 现在在我的主类中,我试图将Application.properites中的所有值加载到

private Properties properties;

So that properties.getProperty("cat") will return "250" 这样properties.getProperty(“ cat”)将返回“ 250”

Not sure how to do it. 不知道该怎么做。 May I get any help on that? 我可以在这方面得到任何帮助吗?

Register your properties file as follows 注册您的属性文件,如下所示

XML Config 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 Config Java配置

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

Using your properties as follows 如下使用属性

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

You can find a complete working solution in my GitHub repository 您可以在我的GitHub存储库中找到完整的工作解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM