A-A+
Jar包的配置文件
前面有篇文章介绍过如何生成一个Jar包(IDEA下创建Jar包),而本文将介绍如何让Jar包调用指定位置的配置文件。如果按照前文生成Jar包,我们的目录是这样的:
其实Jar包内有三个配置文件,我们希望的目录是这样的:
这样做的好处是,我们的开发环境、测试环境、生产环境可以保证每次更新时,只更新jar包,而配置文件不会改变,减少我们每次更新的工作量。
实现的思路很简单,只需要在调用配置文件时,能够动态的识别出文件夹路径即可,使用下面的代码即可:
- public class PathUtil {
- public static String getRootPath(){
- String path = PathUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath();
- if (path.toLowerCase().endsWith(".jar")){
- path = path.substring(0, path.lastIndexOf("/") + 1);
- }
- return path;
- }
- }
在Main函数,或者程序启动时去主动调用上面的方法即可,比如使用log4j的配置文件:
- PropertyConfigurator.configure(PathUtil.getRootPath() + "log4j.properties");
再比如使用spring的配置文件:
- ApplicationContext context = new ClassPathXmlApplicationContext("file:" + PathUtil.getRootPath() + "spring-common.xml");