在Spring Boot的文档spring-boot-devtools 部分,有如下的 描述:

By default, any open project in your IDE will be loaded using the
“restart” classloader, and any regular .jar file will be loaded using
the “base” classloader. If you work on a multi-module project, and not
each module is imported into your IDE, you may need to customize
things. To do this you can create a
META-INF/spring-devtools.properties file.

The spring-devtools.properties file can contain restart.exclude. and
restart.include. prefixed properties. The include elements are items
that should be pulled up into the “restart” classloader, and the
exclude elements are items that should be pushed down into the “base”
classloader. The value of the property is a regex pattern that will be
applied to the classpath.

我遇到的问题是向上转型时出现ClassCastException,按说向上转型是不会出现这个问题的,于是想到可能是ClassLoader不一样导致的,打印了两个对象的ClassLoader,确实不同,一个RestartClassLoader,一个普通的AppClassLoader。

于是在​​Spring Boot DevTools的文档​​文档中找到上面的描述。

解决方案就是在resources目录下面创建META_INF文件夹,然后创建spring-devtools.properties文件,文件加上类似下面的配置:

restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar

All property keys must be unique. As long as a property starts with
restart.include. or restart.exclude. it will be considered. All
META-INF/spring-devtools.properties from the classpath will be loaded.
You can package files inside your project, or in the libraries that
the project consumes.

最佳实践是将本项目中的各个模块的Jar包放到restart.include配置里面。

下面是一篇类似的文章,大家可以看下:使用Spring Boot本地启动,第三方包无法修改项目内静态常量