Spring整合Java读取properties与springboot读取application和自定义properties

Spring整合Java读取properties与springboot读取application和自定义properties

特别说明,本文基于Springboot spring-boot-starter-parent 1.5.1.RELEASE编码,在不同的版本中部分方法有区别


spring中读取配置文件,根据使用场景不同,读取方式也是多种多样,这里浅谈两种场景,当然,这两种场景也不是说是严格区别的。第一种是作为作为参数条件的判断,例如有些常量参数,国际化的东西,你写在配置文件中,可以根据条件加载不同的配置文件,还有一种是某些账号参数,配置参数,需要再启动的时候注入对象中,当然账号这种东西也是可以配置在数据库中,启动的时候加载,这里只是说一种思路。

方式一:代码调用

读取properties的工具类,这种方式是的好处是直接拿到了整个properties对象,可以灵活的做遍历等操作,场景灵活,不足的地方就是要写一大段的代码。

package com.wzh.config.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * <properties解析工具类>
 * <解析properties文件,支持中文,获取classpath下的文件>
 * @author wzh
 * @version 2018-06-24 16:49
 * @see [相关类/方法] (可选)
 **/
public class PropertiesUtils {

    private static Logger log = Logger.getLogger(PropertiesUtils.class);

    /**
     * Spring boot 项目如果直接读取jar包打包方式中的文件
     * 路径会转换为jar:file:/xxxx/xxx
     * 根据配置判断项目打包方式
     */
    private static String PACKAGE_JAR = "0";

    private static String PACKAGE_WAR = "1";

    /**
     * 需要解析的文件后缀
     */
    private static final String FILE_SUFFIX = ".PROPERTIES";

    /**
     * CLASSES文件夹
     */
    private static final String FILE_LOADER = "CLASSES";

    /**
     * 读取classpath指定配置文件返回properties对象
     * @param filePath 文件路径 xxx/xxx
     * @param fileName 文件名xxx.properties
     * @return properties对象
     */
    public static Properties readProperties(String filePath, String fileName) {

        Properties prop=new Properties();
        try {

            //使用spring中的方法获取classes路径下的文件,这里这么做是因为用的springboot,如果打成jar包常用的方法获取不文件
            ClassPathResource classPathResource = new ClassPathResource(filePath + File.separator + fileName);
            InputStream in = classPathResource.getInputStream();

            // 设置UTF-8 支持中文
            Reader reader = new InputStreamReader(in,"UTF-8");
            prop.load(reader);
            if(null != in)
            {
                in.close();
            }

        }catch (Exception e)
        {
            log.error("获取配置文件" + filePath + "失败 " + e.getMessage() ,e);
        }
        return prop;
    }

    /**
     * 获取classpath指定文件夹下所有配置文件,返回Properties对象
     * 这里把解析到的所有实体文件放到一个一个properties中
     * 如果判断实体文件有重复的key,抛出异常
     * @param filePath xxx/xxx
     * @return properties对象
     */
    public static Properties readProperties(String filePath)
    {
        Properties prop = new Properties();

        try {
            // 获取解析的路径
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            URL url = classPathResource.getURL();
            String packagePath = url.toString();

            Properties configProp = readProperties("config/properties","framework.properties");
            String packageType = configProp.getProperty("config.packge.type");
            // jar 打包方式
            if(PACKAGE_JAR.equals(packageType))
            {
                // 获取文件
                getAllFileByFolder(prop, filePath, FILE_SUFFIX);

            }
            // war 打包方式及本地测试
            if(PACKAGE_WAR.equals(packageType)){
                // 获取文件夹下所有文件对象
                List<File> fileList = new ArrayList<File>();
                getAllFileByFolder(filePath, fileList);

                if (!fileList.isEmpty())
                {
                    //转为file为properties对象
                    boolean flag = false;
                    for(File file : fileList)
                    {
                        // file对象转换为properties对象
                        InputStream in = FileUtils.openInputStream(file);
                        // 设置UTF-8 支持中文
                        Reader reader = new InputStreamReader(in,"UTF-8");
                        Properties tempProp = new Properties();
                        tempProp.load(reader);
                        if (null != in)
                        {
                            in.close();
                        }

                        // 组装对象
                        loadProperties(prop,tempProp,filePath);
                    }

                }

            }

        }catch (Exception e)
        {
            log.error(e.getMessage(),e);
        }

        return prop;
    }

    /**
     *获取文件夹下所有文件对象,并返回File对象集合
     * 只能读取文件夹下的文件,不支持jar中读取
     * @param filePath 文件夹路径
     * @param fileList 返回的文件集合
     * @return 文件集合
     * @throws Exception 如果文件夹不存在,抛出业务异常
     */
    public static List<File> getAllFileByFolder(String filePath,List<File> fileList) throws Exception
    {
        //获取路径
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        URL url = classPathResource.getURL();
        log.info(url.toString());
        File file = classPathResource.getFile();
        if(file.exists())
        {
            File[] files = file.listFiles();
            if(files == null || files.length == 0)
            {
                log.warn("文件夹为空:" + filePath);
                return fileList;

            }else{

                for (File temp : files)
                {
                    if(temp.isFile())
                    {
                        fileList.add(temp);
                        log.info("获取文件:" + temp.getName());
                    }else {

                        String newPath = filePath + File.separator + temp.getName();
                        //递归调用
                        getAllFileByFolder(newPath, fileList);
                    }
                }
            }

        }else {
            throw new BusinessException("文件夹不存在:" + filePath);
        }


        return fileList;
    }

    /**
     * 读取jar中的资源文件,classes文件夹下
     * @param filePath 文件路径
     * @param prop 配置文件对象
     * @param fileType 文件类型
     * @return 配置文件对象
     * @throws Exception
     */
    public static Properties getAllFileByFolder(Properties prop,String filePath, String fileType) throws Exception
    {
        // 获取路径
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        URL dirPath = classPathResource.getURL();
        /*
        ----------------------------
         如果工程打为jar 获取的路径大概为:
         jar:file:/Volumes/TOSHIBA/temp/SpringBootDemo.jar!/BOOT-INF/classes!/static/file
         所以根据!/进行拆分
        ----------------------------
         */
        String jarPath = dirPath.toString().substring(0, dirPath.toString().indexOf("!/") + 2);
        // 项目jar url对象
        URL jarURL = new URL(jarPath);
        JarURLConnection jarURLConnection = (JarURLConnection) jarURL.openConnection();

        // 获取jar包中文件目录文件
        JarFile jarFile = jarURLConnection.getJarFile();
        Enumeration<JarEntry> jarEntrys = jarFile.entries();

        // 迭代
        while (jarEntrys.hasMoreElements()){

            // 文件索引对象
            JarEntry jarEntry = jarEntrys.nextElement();
            String fileName = jarEntry.getName();
            log.info(fileName);

            String checkPatch = FILE_LOADER + File.separator +filePath;
            // 只获取指定的文件夹下的指定类型的文件
            if(fileName.toUpperCase().indexOf(checkPatch.toUpperCase()) != -1
                     && fileName.toUpperCase().endsWith(fileType))
            {
                //使用spring中的方法获取classes路径下的文件,这里这么做是因为用的springboot,如果打成jar包常用的方法获取不文件
                ClassPathResource resource = new ClassPathResource(fileName);
                InputStream in = resource.getInputStream();

                // 设置UTF-8 支持中文
                Reader reader = new InputStreamReader(in,"UTF-8");
                Properties tempProp = new Properties();
                tempProp.load(reader);

                if(null != in)
                {
                    in.close();
                }

                // 组装对象
                loadProperties(prop,tempProp,fileName);

            }
        }

        return prop;
    }

    /**
     * 判断重复并合并properties对象
     * @param prop 返回properties对象
     * @param tempProp 需要被合并的临时对象
     * @param filePath 文件路径
     */
    private static void loadProperties(Properties prop,Properties tempProp, String filePath) throws Exception {

        //遍历properties
        Set<Map.Entry<Object, Object>> entrys = tempProp.entrySet();
        for(Map.Entry<Object, Object> entry : entrys)
        {
            String key = (String) entry.getKey();
            // 取不到值加入对象,取得到则properties中key重复,抛出异常
            if(StringUtils.isBlank(prop.getProperty(key)))
            {
                prop.put(entry.getKey(),entry.getValue());
                log.info("成功加载配置文件:" + filePath);

            } else {
                throw new BusinessException("文件夹" + filePath + "下properties key:" + key + " 重复,请核对");
            }
        }
    }
}

简单的工具类,没有经过严格的测试,如果需要拿到项目中用,需要再测试一下。这个工具类中有点点小的配置,是为了兼容在本地ide测试的时候war包,jar包打包方式后读取classes目录下文件写的,在打包成jar之后,读取jar中的资源文件只能通过流的方式,直接用获取File的方式是无法读取,会报错了。
解决方式可以用通过classLoader加载文件流读取。

org.springframework.util.ClassUtils.class.getClassLoader().getResourceAsStream(filePath)

其中filepath为相对于classpath的路径,不能以/开头。也可以用上面写的工具类读取,方式多种多样,核心思路就是流。
工具类代码中有加载判断打包方式,这里只是通过读取配置文件在文件中直接配置好是jar还是war打包,具体判断方式根据自身的实际情况判断。

            Properties configProp = readProperties("config/properties","framework.properties");
            String packageType = configProp.getProperty("config.packge.type");
            // jar 打包方式
            if(PACKAGE_JAR.equals(packageType))
            {
                // 获取文件
                getAllFileByFolder(prop, filePath, FILE_SUFFIX);

            }
            // war 打包方式及本地测试
            if(PACKAGE_WAR.equals(packageType)){
                ......
            }

自己写的配置文件

## ftp系统加载开关 0表示打开,1表示关闭
config.ftp.switch=1
## 项目打包方式 0表示 JAR 1表示WAR
config.packge.type=1

工具类中有大体有两个方式,一个是获取指定的配置文件,一个是获取某个文件夹下的文件所有配置文件,获取指定的配置文件的方法可以用作配置参数判断的场景,例如我在工具类中判断打包方式的用法。获取某个文件夹下的所有文件,一般用作国际化等场景,根据不同的场景在项目启动的时候一次性把配置文件的内容加载到内存中,然后在需要的地方取用。

方式二:springboot注解式

这种方式的优势就是不自己写代码去读取,框架帮我们完成操作,不足之处就是不够灵活,不过注解式常用的场景也覆盖了。
注解式读取自定义配置文件需要用到两个注解 @PropertySource@Value 。这里特别说明下,在spring 1.5以前一般是用 @ConfigurationProperties 不过1.5以后把locations这个参数移除了,所有就没法指定配置文件的路径了,改用 @PropertySource

@ConfigurationProperties
常用属性:
locations:指定配置文件
prefix:指定该配置文件中的某个属性群的前缀
@PropertySource
常用属性:
value:指定配置文件,替代原来@ConfigurationProperties的locations,多个引用逗号隔开
@PropertySource({"classpath:config/xx.properties","classpath:config/config.properties"})
encoding:指定读取配置文件时的编码

下面来展示一下怎么配合使用:
1.测试用的配置文件test.properties,放在resources资源文件夹下,打包的时候会到classes下面

test.name=小明
test.age=25
test.sex=男

2.测试用映射类,省略get set toString方法。这里特别说明下,不管是bean也好controller也好,和标记为容器管理的对象用的注解没有直接关系,例如@Component@Controller 没有什么关系,只要PropertySource和Value组合使用就可以了。

/**
 * <注解读取配置文件测试类>
 * <功能详细描述>
 * @author wzh
 * @version 2018-06-30 18:55
 * @see [相关类/方法] (可选)
 **/
public class PropertiesTestBean {

    private String name;
    private String sex;
    private Long age;
}

3.使用注解注入属性,注解注入属性的方式有两种,第一种是单个注入,还有一种是一次性注入,自动绑定

单个注入

package com.wzh.demo.domain;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * <注解读取配置文件测试类>
 * <功能详细描述>
 * @author wzh
 * @version 2018-06-30 18:55
 * @see [相关类/方法] (可选)
 **/
@Component
@PropertySource(value = "classpath:static/file/test.properties",encoding = "utf-8")
public class PropertiesTestBean {

    //在application.properties中的文件,直接使用@Value读取即可,applicarion的读取优先级最高

    @Value("${test.name}")
    private String name;

    @Value("${test.sex}")
    private String sex;

    @Value("${test.age}")
    private Long age;
    
    //省略get set toString方法..........
}

junit 测试类

import base.BaseJunit;
import com.wzh.config.utils.PropertiesUtils;
import com.wzh.demo.domain.PropertiesTestBean;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * <一句话功能描述>
 * <功能详细描述>
 *
 * @author wzh
 * @version 2018-06-24 20:20
 * @see [相关类/方法] (可选)
 **/
public class PropertiesTest extends BaseJunit{

    @Autowired
    PropertiesTestBean propertiesTestBean;

    @Test
    public void test()
    {
        System.out.println(propertiesTestBean.toString());
    }

}

控制台成功过输出


image.png

还是刚刚的对象,复制一份,展示一下批量注入,需注意,批量注入自动映射的时候,属性名需要和配置文件中的相同。
这里需要注意,之前测试用配置文件用的相同的prefix,所有可以使用@ConfigurationProperties注解中的prefix属性指定prefix,使用这个注解后IDEA可能会提示报错。

  1. Spring Boot Annotion processor not found in classpath
  2. Re-run Spring Boot Configuration Annotation Processor to update generated metadata
image.png
image.png

这个是因为在高版本的spring中Configuration去除了locations,这个注解默认在resources目录下,编译后在classes文件夹下去找配置文件,找不到对应的就提示。根据提示官方给出的解决方案是导入依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

导入这个更新maven后报错就变为Re-run Spring Boot Configuration Annotation Processor to update generated metadata。提示要求重新编译,尝试了多种方式,都不能消除这个警告,不过不用管它,能正常运行。测试不导入提示的依赖,在报Spring Boot Annotion processor not found in classpath 的情况下运行,也没有问题,只要用了 @PropertySource 注解指定了路径。

测试类

package com.wzh.demo.domain;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * <注解读取配置文件测试类>
 * <功能详细描述>
 * @author wzh
 * @version 2018-06-30 18:55
 * @see [相关类/方法] (可选)
 **/
@Component
@PropertySource(value = "classpath:static/file/test.properties",encoding = "utf-8")
@ConfigurationProperties(prefix="test")
public class PropertiesTestBean1 {

    //在application.properties中的文件,直接使用@Value读取即可,applicarion的读取优先级最高

    private String name;

    private String sex;

    private Long age;

    //省略get set toString方法..........
}

junit测试类

import base.BaseJunit;
import com.wzh.config.utils.PropertiesUtils;
import com.wzh.demo.domain.PropertiesTestBean;
import com.wzh.demo.domain.PropertiesTestBean1;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * <一句话功能描述>
 * <功能详细描述>
 *
 * @author wzh
 * @version 2018-06-24 20:20
 * @see [相关类/方法] (可选)
 **/
public class PropertiesTest extends BaseJunit{

    @Autowired
    PropertiesTestBean propertiesTestBean;

    @Autowired
    PropertiesTestBean1 propertiesTestBean1;

    @Test
    public void test()
    {
        System.out.println(propertiesTestBean1.toString());
    }

}

控制台成功输出


image.png

这里做个记录,也希望这篇文章对大家有所帮助。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容