zoukankan      html  css  js  c++  java
  • springboot获取当前项目绝对路径和根目录

    springboot获取当前项目路径的地址

    System.getProperty("user.dir")

    输出目录:  G:outshinewangsoso

    //获取classes目录绝对路径

    String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

    String path = ResourceUtils.getURL("classpath:").getPath();

    输出目录:  /G:/outshine/wangsoso/target/classes/

    //如果上传目录为/static/images/upload/,则可以如下获取:
    File upload = new File(path.getAbsolutePath(),"static/images/upload/");
    if(!upload.exists()) upload.mkdirs();
    System.out.println("upload url:"+upload.getAbsolutePath());
    //在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
    //在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/

    注意:以jar包发布项目时,我们存储的路径是与jar包同级的static目录,因此我们需要在jar包目录的application.properties配置文件中设置静态资源路径,如下所示:

    #设置静态资源路径,多个以逗号分隔

    spring.resources.static-locations=classpath:static/,file:static/

    以jar包发布springboot项目时,默认会先使用jar包跟目录下的application.properties来作为项目配置文件。

    如果在不同的目录中存在多个配置文件,它的读取顺序是:

            1、config/application.properties(项目根目录中config目录下)

            2、config/application.yml

            3、application.properties(项目根目录下)

            4、application.yml

            5、resources/config/application.properties(项目resources目录中config目录下)

            6、resources/config/application.yml

            7、resources/application.properties(项目的resources目录下)

            8、resources/application.yml

    注:

         1、如果同一个目录下,有application.yml也有application.properties,默认先读取application.properties。

         2、如果同一个配置属性,在多个配置文件都配置了,默认使用第1个读取到的,后面读取的不覆盖前面读取到的。

         3、创建SpringBoot项目时,一般的配置文件放置在“项目的resources目录下”

     /**
         * 获取项目根路径
         *
         * @return
         */
        private static String getResourceBasePath() {
            // 获取跟目录
            File path = null;
            try {
                path = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                // nothing to do
            }
            if (path == null || !path.exists()) {
                path = new File("");
            }
    
            String pathStr = path.getAbsolutePath();
            // 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
            pathStr = pathStr.replace("\target\classes", "");
    
            return pathStr;
        }
    
  • 相关阅读:
    CF85E Guard Towers(二分答案+二分图)
    CF732F Tourist Reform(边双联通)
    CF949C Data Center Maintenance(建图+强联通分量)
    CF402E Strictly Positive Matrix(矩阵,强联通分量)
    CF209C Trails and Glades(欧拉路)
    POJ1201Intervals(差分约束)
    NOIP2016 天天爱跑步(树上差分)
    CF19E Fairy(树上差分)
    NOIP 2017 小凯的疑惑(同余类)
    POJ 3539 Elevator(同余类BFS)
  • 原文地址:https://www.cnblogs.com/QuickSlow/p/12751877.html
Copyright © 2011-2022 走看看