比properties更好用的读配置文件的方式

Posted Z-hhhhh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了比properties更好用的读配置文件的方式相关的知识,希望对你有一定的参考价值。

用properties.load()时总是要求改level为6,很不舒服
学习了用别的方式读配置文件

案例如下:

一、需要的依赖有:

 <!--log4j日志核心包-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <!--xml解析核心包-->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.jdom</groupId>
            <artifactId>jdom2</artifactId>
            <version>2.0.5</version>
        </dependency>

<build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.log</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!-- mybatis generator 自动生成代码插件 和本案例无关 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>$basedir/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.Test</mainClass>
                                </transformer>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.handlers</resource>
                                </transformer>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.schemas</resource>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

二、前提工作

resources里建 config和generator包
config里放配置文件,因为test和生产环境不一样,所以用这种方式
test.properties

cloud.mysql.jdbc.driver=com.mysql.cj.jdbc.Driver

和config同级中放config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <!--测试环境-->
    <properties resource="config/test.properties"></properties>

</configuration>

三、configuration工具

constant包中放configuration 代码如下

package constant;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author zwh
 * @date 2022/4/20
 */
public class Configuration extends Properties 
    public static final Logger log = LogManager.getLogger(Configuration.class);
    private static final long serialVersionUID = 50440463580273222L;

    private static Configuration instance = null;

    public Configuration() 
        InputStream in;
        try 
            in = this.getClass().getResourceAsStream("/"+ read());
            this.load(in);
            in.close();
         catch (IOException e) 
            // TODO Auto-generated catch block
            log.error(e);
        

    

    public static synchronized Configuration getInstance() 
        if (instance == null) 
            instance = new Configuration();
        
        return instance;
    

    public String read() 
        String prefix = null;
        SAXBuilder builder = new SAXBuilder();
        InputStream file = this.getClass().getResourceAsStream("/config.xml");

        try 
            Document doc = builder.build(file);//获得文档对象
            Element root = doc.getRootElement();//获得根节点
            List<Element> list = root.getChildren();
            for (Element e : list) 
                if (null != e.getAttribute("resource")) 
                    prefix = e.getAttribute("resource").getValue();
                
            
         catch (Exception e) 
            log.error(e);
        
        return prefix;
    

    @Override
    public String getProperty(String key, String defaultValue) 
        String val = getProperty(key);
        return (val == null || val.isEmpty()) ? defaultValue : val;
    

    public String getString(String name, String defaultValue) 
        return this.getProperty(name, defaultValue);
    

    public int getInt(String name, int defaultValue) 
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    

    public long getLong(String name, long defaultValue) 
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    

    public float getFloat(String name, float defaultValue) 
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Float.parseFloat(val);
    

    public double getDouble(String name, double defaultValue) 
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Double.parseDouble(val);
    

    public byte getByte(String name, byte defaultValue) 
        String val = this.getProperty(name);
        return (val == null || val.isEmpty()) ? defaultValue : Byte.parseByte(val);
    


四、测试

写好了 最后测试一下

package com;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * @author zwh
 * @date 2022/4/20
 */
public class Test 
    public static final Logger log = LogManager.getLogger(Test.class);
    public static constant.Configuration config = constant.Configuration.getInstance();

    public static void main(String[] args) 

        String driverClassName = config.getString("cloud.mysql.jdbc.driver", "");

        System.out.println(driverClassName);
    


这样比直接用properties确实好用多了

以上是关于比properties更好用的读配置文件的方式的主要内容,如果未能解决你的问题,请参考以下文章

springboot:springboot的配置(yaml文件方式和properties文件方式)

MyBatis配置文件之properties属性

java中读取配置文件ResourceBundle和Properties两种方式比较

比 UICollectionView更好用的IGListKit教程

SqlHelper发布—比Pagehelper更好用的分页插件

比cat更好用的命令!