1.首先怎么用maven将src/main/resources下的配置文件打入jar包中呢?
在pom文件中配置:
<build>
<!-- finalName:指定maven打包后的包名-->
<finalName>test-${version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
然后运行 mvn install 就可以在target目录下看到jar包了
解压jar包,可以确认配置文件是否打进去了
2.加载jar包中的配置文件,转化为Properties对象
踩坑实践:
String path = Thread.currentThread().getContextClassLoader().getResource(HTTP_PROP_NAME).getPath();//得到配置文件路径
Properties properties = properties.load(new FileReader(path));//转化为Properties对象
运行程序一直报空指针
debug调试后,发现path的值为:test-0.0.1.jar!/config/httpclient-config.properties
注意看.jar后面是个感叹号,然后拼接的配置文件相对地址
为什么会加载不到呢?
对于文件系统来说,jar是一个文件,文件里面怎么还可以包含文件路径呢?test-0.0.1.jar!/config/httpclient-config.properties这个地址对于文件系统来说,根本就不存在,所以通过这个地址来new file,文件肯定不存在啥。
那该怎么加载呢?
通过类加载器得到配置文件的输入流
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(HTTP_PROP_NAME);
Properties properties = properties.load(inputStream);
这样就把配置文件转为properties对象了
获取配置文件中的内容就简单了properties.getProperty(“test”);