gradle项目中资源文件的相对路径打包处理技巧

隧洞衬砌
gradle项⽬中资源⽂件的相对路径打包处理技巧
开发java application时,不管是⽤ant/maven/gradle中的哪种⽅式来构建,通常最后都会打包成⼀个可执⾏的jar包程序,⽽程序运⾏所需的⼀些资源⽂件(配置⽂件),⽐如jdbc.properties, l,l这些,可以⼀起打包到jar中,程序运⾏时⽤类似
classpath*:l的去加载,⼤多数情况下,这样就能⼯作得很好了。
但是,如果有⼀天,需要修正配置,⽐如:⼀个应⽤上线初期,为了调试⽅便,可能会把log的⽇志级别设置低⼀些,⽐如:INFO级别,运⾏⼀段时间稳定以后,只需要记录WARN或ERROR级别的⽇志,这时候就需要修改l之类的配置⽂件,如果把配置⽂件打包在jar ⽂件内部,改起来就⽐较⿇烦,要把重新打包部署,要么在线上,先⽤jar命令将jar包解压,改好后,再打包回去,⽐较繁琐。
⾯对这种需求,更好的⽅式是把配置⽂件放在jar⽂件的外部相对⽬录下,程序启动时去加载相对⽬录下的配置⽂件,这样改起来,就⽅便多了,下⾯演⽰如何实现:(以gradle项⽬为例)
主要涉及以下⼏点:
1、如何不将配置⽂件打包到jar⽂件内
既然配置⽂件放在外部⽬录了,jar⽂件内部就没必要再重复包含这些⽂件了,可以修改adle⽂件,参考下⾯这样:
processResources {
exclude { "**/*.*" }
}
相当于覆盖了默认的processResouces task,这样gradle打包时,资源⽬录下的任何⽂件都将排除。
2、log4j2的配置加载处理
log4j2加载配置⽂件时,默认情况下会classpath下的l⽂件,除⾮⼿动给它指定配置⽂件的位置,分析它的源码,可以到下⾯这段:org.apache.onfig.ConfigurationFactory.Factory#getConfiguration(java.lang.String, java.URI)
1public Configuration getConfiguration(final String name, final URI configLocation) {
2
3if (configLocation == null) {
4final String configLocationStr = Properties()
5                        .getStringProperty(CONFIGURATION_FILE_PROPERTY));
6if (configLocationStr != null) {
7                    ConfigurationSource source = null;
8try {
9                        source = URI(configLocationStr));
10                    } catch (final Exception ex) {
11// Ignore the error and try as a String.
12                        LOGGER.catching(Level.DEBUG, ex);
13                    }
电动卷帘门控制器
14if (source == null) {
15final ClassLoader loader = ThreadContextClassLoader();
16                        source = getInputFromString(configLocationStr, loader);
17                    }幻听的中药
18if (source != null) {
19for (final ConfigurationFactory factory : getFactories()) {
20final String[] types = SupportedTypes();
21if (types != null) {
22for (final String type : types) {
23if (type.equals("*") || dsWith(type)) {
24final Configuration config = Configuration(source);
25if (config != null) {
26return config;
27                                        }
28                                    }
29                                }
30                            }
31                        }
32                    }
33                } else {
34for (final ConfigurationFactory factory : getFactories()) {
35final String[] types = SupportedTypes();
36if (types != null) {
37for (final String type : types) {
38if (type.equals("*")) {
39final Configuration config = Configuration(name, configLocation);
40if (config != null) {
41return config;
HDPE多孔加筋缠绕波纹管42                                    }
43                                }
钯铂催化剂回收44                            }
45                        }
46                    }
47                }
48            } else {
49// configLocation != null
50final String configLocationStr = String();
51for (final ConfigurationFactory factory : getFactories()) {
52final String[] types = SupportedTypes();
53if (types != null) {
54for (final String type : types) {
55if (type.equals("*") || dsWith(type)) {
56final Configuration config = Configuration(name, configLocation);
57if (config != null) {
58return config;
59                                }
60                            }
61                        }
62                    }
63                }
64            }
65
66            Configuration config = getConfiguration(true, name);
67if (config == null) {
68                config = getConfiguration(true, null);
69if (config == null) {
70                    config = getConfiguration(false, name);
71if (config == null) {
72                        config = getConfiguration(false, null);
73                    }
74                }
75            }
76if (config != null) {
77return config;
78            }
79            ("No log4j2 configuration file found. Using default configuration: logging only errors to the console.");
80return new DefaultConfiguration();
81        }
View Code
其中常量CONFIGURATION_FILE_PROPERTY的定义为:
public static final String CONFIGURATION_FILE_PROPERTY = "figurationFile";
View Code
从这段代码可以看出,只要在第⼀次调⽤log4j2的getLogger之前设置系统属性,将其指到配置⽂件所在的位置即可。
3、其它⼀些配置⽂件(⽐如spring配置)的相对路径加载
这个⽐较容易,spring本⾝就⽀持从⽂件⽬录加载配置的能⼒。
综合以上分析,可以封装⼀个⼯具类:
1import t.ConfigurableApplicationContext;
2import t.support.FileSystemXmlApplicationContext;
3
4import java.io.File;
5
6
7public class ApplicationContextUtil {
8
9private static ConfigurableApplicationContext context = null;
10
11private static ApplicationContextUtil instance = null;
12
13public static ApplicationContextUtil getInstance() {
14if (instance == null) {
15synchronized (ApplicationContextUtil.class) {
16if (instance == null) {
17                    instance = new ApplicationContextUtil();
18                }
19            }
20        }
21return instance;
22    }
23
24public ConfigurableApplicationContext getContext() {
25return context;
26    }
27
28private ApplicationContextUtil() {
29
30    }
31
32
33static {
34
35//加载l
36        String configLocation = "l";
37        File configFile = new File(configLocation);
38if (!ists()) {
39            println("log4j2 config file:" + AbsolutePath() + " not exist");
40            it(0);
41        }
42        System.out.println("log4j2 config file:" + AbsolutePath());
43
44try {
45//注:这⼀句必须放在整个应⽤第⼀次Logger(XXX.class)前执⾏
46            System.setProperty("figurationFile", AbsolutePath());
47        } catch (Exception e) {
48            println("log4j2 initialize error:" + e.getLocalizedMessage());
49            it(0);
50        }
51
52//加载spring配置⽂件
53        configLocation = "l";
54        configFile = new File(configLocation);
55
56if (!ists()) {
57            println("spring config file:" + AbsolutePath() + " not exist");
58            it(0);
59        }
60
61        System.out.println("spring config file:" + AbsolutePath());
62
63if (context == null) {
64            context = new FileSystemXmlApplicationContext(configLocation);
65            System.out.println("spring load success!");
66        }
67
68    }
69
70
71 }
View Code
注:这⾥约定了配置⽂件放在相对⽬录resources下,⽽且log4j2的配置⽂件名为l,spring的⼊⼝配置⽂件为l(如果不想按这个约定来,可参考这段代码⾃⾏修改)
有了这个⼯具类,mainclass⼊⼝程序上可以这么⽤:
1import org.slf4j.Logger;
2import org.slf4j.LoggerFactory;
3import t.ApplicationContext;
4
5/**
6 * Created by yangjunming on 12/15/15.
7 * author: yangjunming@huijiame
8*/
9public class App {
10
11private static ApplicationContext context;
12private static Logger logger;
13
14
15public static void main(String[] args) {
16
17        context = Instance().getContext();
18        logger = Logger(App.class);
19
20        System.out.println("start ...");
21软轴泵
22        logger.debug("debug message");
23
24        logger.info("info message");
25
26        logger.warn("warn message");
27
28        ("error message");
29
30        System.out.Bean(SampleObject.class));
31
32    }
33 }
View Code
再次友情提醒:logger的实例化,⼀定要放在Instance().getContext();之后,否则logger在第⼀次初始化时,仍然尝试会到classpath下去l⽂件,实例化之后,后⾯再设置系统属性就没⽤了。
4、gradle 打包的处理
代码写完了,还有最后⼀个⼯作没做,既然配置⽂件不打包到jar⾥了,那就得复制到jar包的相对⽬录resources下,可以修改adle脚本,让计算机处理处理,在代替⼿动复制配置⽂件。
task pack(type: Copy, dependsOn: [clean, installDist]) {
sources.srcDirs.each {
from it
into "$buildDir/install/$rootProject.name/bin/resources"
}
}
增加这个task后,直接⽤gradle pack就可以实现打包,并⾃动复制配置⽂件到相对⽬录resources⽬录下了,参考下图:
gradle pack 后,可进⼊build/install/config-load-demo/bin ⽬录,运⾏./config-load-demo (windows下运⾏config-load-demo.bat) 查看效果,然后尝试修改l⾥的⽇志级别,再次运⾏,观察变化。

本文发布于:2024-09-24 21:20:03,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/2/178293.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:配置   打包   处理
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议