打包优化分离配置文件后,服务器部署时logback.xml加载有问题。问题就是,在ide中需要设置classpath路径,服务器部署需要设置file路径
ide中运行和测试:
#配置外部logback.xml
logging:
config: classpath:./config/logback.xml
服务器部署:
#配置外部logback.xml
logging:
config: file:./config/logback.xml
以下都是在服务器上部署的加载测试
一、设置成classpath
1、classpath:./config/logback.xml
启动报错:
Logging system failed to initialize using configuration from 'classpath:./config/logback.xml'
java.io.FileNotFoundException: class path resource [./config/logback.xml] cannot be resolved to URL because it does not exist
2、classpath:config/logback.xml
同样报错:
Logging system failed to initialize using configuration from 'classpath:config/logback.xml'
java.io.FileNotFoundException: class path resource [config/logback.xml] cannot be resolved to URL because it does not exist
3、classpath:/config/logback.xml
同样报错:
Logging system failed to initialize using configuration from 'classpath:/config/logback.xml'
java.io.FileNotFoundException: class path resource [/config/logback.xml] cannot be resolved to URL because it does not exist
二、设置成file
1、file:./config/logback.xml
取当前目录下,可以加载
2、file:config/logback.xml
取相对目录,可以加载
3、file:/config/logback.xml
从根目录找,启动报错:
Logging system failed to initialize using configuration from 'file:/config/logback.xml'
java.io.FileNotFoundException: /config/logback.xml (No such file or directory)
三、启动命令中添加calsspath
-Xbootclasspath/a:./ :将classpath添加在核心class搜索路径后面
作用是添加当前目录(可执行的jar所在的目录)到classpath
使用以下命令启动:
java -Xbootclasspath/a:./ -jar myboot-0.0.1-SNAPSHOT.jar --spring.config.location=file:./config/
1、classpath:./config/logback.xml
可以加载
2、classpath:config/logback.xml
可以加载
3、classpath:/config/logback.xml
启动报错:
Logging system failed to initialize using configuration from 'classpath:/config/logback.xml'
java.io.FileNotFoundException: class path resource [/config/logback.xml] cannot be resolved to URL because it does not exist
四、小结
1、使用springboot添加classpath的设置,可以解决logback.xml加载问题
2、路径设置成./config/logback.xml和config/logback.xml都可以,不要设置成绝对路径
五、新增方法
自定义MANIFEST.MF中的Class-Path
修改pom文件maven-jar-plugin插件的配置,添加:
<manifestEntries>
<Class-Path>. config/</Class-Path>
</manifestEntries>
就是把 . 和 config/ 加入Class-Path路径,完整效果:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<!--是否要把第三方jar放到manifest.mf的classpath中 -->
<addClasspath>true</addClasspath>
<!--生成的manifest.mf中classpath的前缀,因为要把第三方jar放到lib目录下,所以classpath的前缀是lib/ -->
<classpathPrefix>lib/</classpathPrefix>
<!-- 执行的主程序路径 -->
<mainClass>com.blemall.crcs.main.CrcsApplication</mainClass>
</manifest>
<manifestEntries>
<Class-Path>. config/</Class-Path>
</manifestEntries>
</archive>
<!-- 排除target/classes下的config目录 -->
<excludes>
<exclude>config/**</exclude>
</excludes>
</configuration>
</plugin>
这样不需要加-Xbootclasspath/a:./ 也能加载logback.xml文件
参考资料:
JAVA 运行springboot jar包设置classpath - 季枫 - 博客园
MANIFEST.MF文件详解 - 隐官陈十一 - 博客园 (cnblogs.com)
注:最新代码上传至https://github.com/csj50/myboot