美文网首页
Spring整合Java读取properties与springb

Spring整合Java读取properties与springb

作者: TryCatch菌 | 来源:发表于2018-10-05 01:10 被阅读0次

    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

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

    相关文章

      网友评论

          本文标题:Spring整合Java读取properties与springb

          本文链接:https://www.haomeiwen.com/subject/ambvoftx.html