许多相同的属性会像实例列表一样

时间:2019-04-16 09:18:21

标签: spring-boot application.properties

如何在application.properties中准备属性,以便在Java方面像列表一样

server.ip=192.168.0.0
server.login=login1
server.password=password1

server.ip=192.168.0.1
server.login=login2
server.password=password2

最初的属性位于xml中,但想要替换为.properties

<servers>
    <server>
        <url>https://192.168.0.0</url>
        <username>login1</username>
        <password>password1</password>
    </server>
    <server>
        <url>https://192.168.0.1</url>
        <username>login2</username>
        <password>password2</password>
    /server>    
</servers>

2 个答案:

答案 0 :(得分:0)

下面的示例从XML文件创建.properties文件。该代码可用于从XML文件读取属性键值,以在应用程序代码中使用。

package xyz.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class XMLToProperties
{
    public static void main(String[] args) throws InvalidPropertiesFormatException, IOException
    {
        String outPropertiesFile = "application.properties";
        String inXmlFile = "applicationProperties.xml";

        InputStream inStream = new FileInputStream(inXmlFile);          //Input XML File
        OutputStream outStream = new FileOutputStream(outPropertiesFile);   //Output properties File

        Properties props = new Properties();

        //Load XML file
        props.loadFromXML(inStream);

        //Store to properties file
        props.store(outStream, "Converted from applicationProperties.xml");

        //Use properties in code
        System.out.println(props.get("input.dir"));         //Prints 'c:/temp/input'
    }
}
  

applicationProperties.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>application.properties</comment>
    <entry key="input.dir">c:/temp/input</entry>
    <entry key="spring.batch.job.enabled">false</entry>
    <entry key="spring.main.banner-mode">off</entry>
</properties>
  

application.properties

#Converted from applicationProperties.xml
#Mon Jul 23 18:15:00 IST 2018

spring.batch.job.enabled=false
input.dir=c\:/temp/input
spring.main.banner-mode=off

此处有更多详细信息:https://howtodoinjava.com/xml/convert-xml-to-properties/

答案 1 :(得分:0)

请参阅this

您应该维护格式正确的xml文件,如下所示。

 <server>
        <ip>192.168.0.0</ip>
 </server>