开发java application时,不管是用ant/maven/gradle中的哪种方式来构建,通常最后都会打包成一个可执行的jar包程序,而程序运行所需的一些资源文件(配置文件),比如jdbc.properties, log4j2.xml,spring-xxx.xml这些,可以一起打包到jar中,程序运行时用类似classpath*:xxx.xml的去加载,大多数情况下,这样就能工作得很好了。
但是,如果有一天,需要修正配置,比如:一个应用上线初期,为了调试方便,可能会把log的日志级别设置低一些,比如:info级别,运行一段时间稳定以后,只需要记录warn或error级别的日志,这时候就需要修改log4j2.xml之类的配置文件,如果把配置文件打包在jar文件内部,改起来就比较麻烦,要把重新打包部署,要么在线上,先用jar命令将jar包解压,改好后,再打包回去,比较繁琐。
面对这种需求,更好的方式是把配置文件放在jar文件的外部相对目录下,程序启动时去加载相对目录下的配置文件,这样改起来,就方便多了,下面演示如何实现:(以gradle项目为例)
主要涉及以下几点:
1、如何不将配置文件打包到jar文件内
既然配置文件放在外部目录了,jar文件内部就没必要再重复包含这些文件了,可以修改build.gradle文件,参考下面这样:
processresources {
exclude { "**/*.*" }
}
相当于覆盖了默认的processresouces task,这样gradle打包时,资源目录下的任何文件都将排除。
2、log4j2的配置加载处理
log4j2加载配置文件时,默认情况下会找classpath下的log4j2.xml文件,除非手动给它指定配置文件的位置,分析它的源码,
可以找到下面这段:
org.apache.logging.log4j.core.config.configurationfactory.factory#getconfiguration(java.lang.string, java.net.uri)
public configuration getconfiguration(final string name, final uri configlocation) {
if (configlocation == null) {
final string configlocationstr = this.substitutor.replace(propertiesutil.getproperties()
.getstringproperty(configuration_file_property));
if (configlocationstr != null) {
configurationsource source = null;
try {
source = getinputfromuri(netutils.touri(configlocationstr));
} catch (final exception ex) {
// ignore the error and try as a string.
logger.catching(level.debug, ex);
}
if (source == null) {
final classloader loader = loaderutil.getthreadcontextclassloader();
source = getinputfromstring(configlocationstr, loader);
}
if (source != null) {
for (final configurationfactory factory : getfactories()) {
final string[] types = factory.getsupportedtypes();
if (types != null) {
for (final string type : types) {
if (type.equals("*") || configlocationstr.endswith(type)) {
final configuration config = factory.getconfiguration(source);
if (config != null) {
return config;
}
}
}
}
}
}
} else {
for (final configurationfactory factory : getfactories()) {
final string[] types = factory.getsupportedtypes();
if (types != null) {
for (final string type : types) {
if (type.equals("*")) {
final configuration config = factory.getconfiguration(name, configlocation);
if (config != null) {
return config;
}
}
}
}
}
}
} else {
// configlocation != null
final string configlocationstr = configlocation.tostring();
for (final configurationfactory factory : getfactories()) {
final string[] types = factory.getsupportedtypes();
if (types != null) {
for (final string type : types) {
if (type.equals("*") || configlocationstr.endswith(type)) {
final configuration config = factory.getconfiguration(name, configlocation);
if (config != null) {
return config;
}
}
}
}
}
}
configuration config = getconfiguration(true, name);
if (config == null) {
config = getconfiguration(true, null);
if (config == null) {
config = getconfiguration(false, name);
if (config == null) {
config = getconfiguration(false, null);
}
}
}
if (config != null) {
return config;
}
logger.error("no log4j2 configuration file found. using default configuration: logging only errors to the console.");
return new defaultconfiguration();
}
其中常量configuration_file_property的定义为:
public static final string configuration_file_property = "log4j.configurationfile";
从这段代码可以看出,只要在第一次调用log4j2的getlogger之前设置系统属性,将其指到配置文件所在的位置即可。
3、其它一些配置文件(比如spring配置)的相对路径加载
这个比较容易,spring本身就支持从文件目录加载配置的能力。
综合以上分析,可以封装一个工具类:
import org.springframework.context.configurableapplicationcontext;
import org.springframework.context.support.filesystemxmlapplicationcontext;
import java.io.file;
public class applicationcontextutil {
private static configurableapplicationcontext context = null;
private static applicationcontextutil instance = null;
public static applicationcontextutil getinstance() {
if (instance == null) {
synchronized (applicationcontextutil.class) {
if (instance == null) {
instance = new applicationcontextutil();
}
}
}
return instance;
}
public configurableapplicationcontext getcontext() {
return context;
}
private applicationcontextutil() {
}
static {
//加载log4j2.xml
string configlocation = "resources/log4j2.xml";
file configfile = new file(configlocation);
if (!configfile.exists()) {
system.err.println("log4j2 config file:" + configfile.getabsolutepath() + " not exist");
system.exit(0);
}
system.out.println("log4j2 config file:" + configfile.getabsolutepath());
try {
//注:这一句必须放在整个应用第一次loggerfactory.getlogger(xxx.class)前执行
system.setproperty("log4j.configurationfile", configfile.getabsolutepath());
} catch (exception e) {
system.err.println("log4j2 initialize error:" + e.getlocalizedmessage());
system.exit(0);
}
//加载spring配置文件
configlocation = "resources/spring-context.xml";
configfile = new file(configlocation);
if (!configfile.exists()) {
system.err.println("spring config file:" + configfile.getabsolutepath() + " not exist");
system.exit(0);
}
system.out.println("spring config file:" + configfile.getabsolutepath());
if (context == null) {
context = new filesystemxmlapplicationcontext(configlocation);
system.out.println("spring load success!");
}
}
}
注:这里约定了配置文件放在相对目录resources下,而且log4j2的配置文件名为log4j2.xml,spring的入口配置文件为spring-context.xml(如果不想按这个约定来,可参考这段代码自行修改)
有了这个工具类,mainclass入口程序上可以这么用:
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.context.applicationcontext;
/**
* created by yangjunming on 12/15/15.
* author: yangjunming@huijiame.com
*/
public class app {
private static applicationcontext context;
private static logger logger;
public static void main(string[] args) {
context = applicationcontextutil.getinstance().getcontext();
logger = loggerfactory.getlogger(app.class);
system.out.println("start ...");
logger.debug("debug message");
logger.info("info message");
logger.warn("warn message");
logger.error("error message");
system.out.println(context.getbean(sampleobject.class));
}
}
再次友情提醒:logger的实例化,一定要放在applicationcontextutil.getinstance().getcontext();之后,否则logger在第一次初始化时,仍然尝试会到classpath下去找log4j2.xml文件,实例化之后,后面再设置系统属性就没用了。
4、gradle 打包的处理
代码写完了,还有最后一个工作没做,既然配置文件不打包到jar里了,那就得复制到jar包的相对目录resources下,可以修改build.gradle脚本,让计算机处理处理,在代替手动复制配置文件。
task pack(type: copy, dependson: [clean, installdist]) {
sourcesets.main.resources.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) 查看效果,然后尝试修改resources/log4j2.xml里的日志级别,再次运行,观察变化 。
以上这篇gradle项目中资源文件的相对路径打包技巧必看就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持萬仟网。
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!