SpringBoot系列:Spring Boot热部署,集成devtools

工欲善其事,必先利其器,好的编码环境能让我们事半功倍。熟悉前端的可能都知道热部署,如Vue、AngularJS等保存便自动编译,无需重启的酣畅淋漓,羡煞不已。

其实完全用不着羡慕,在Spring Boot里,一切皆有可能,今天,热部署,他来了。

一、Spring Boot DevTools

Spring Boot DevTools使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为restart ClassLoader,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,重新创建一个restart ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间。

所以,妈妈再也不用担心我改完代码编译时间太长了。

devtools配置比较简单,在Eclipse和IDEA上略有不同。

Eclipse配置devtools

首先我们需要引入spring-boot-devtools依赖,然后并设置spring-boot-maven-plugin下configuration的fork节点值为true。

然后开启eclipse的自动编译即可。

IDEA配置devtools

对于IDEA,同样的,我们需要引入spring-boot-devtools,并设置fork节点为true,这个和Eclipse是一样的。

然后打开File-Settings-Compiler,找到并勾选Make Project automatically。

再快捷键ctrl + shift + alt + /,选择Registry,勾上 Compiler autoMake allow when app running,就配置完成了。

二、示例演示

既然devtools已经配置完毕,那我们赶快来体验一下吧。

这里简单创建了一个controller,里面就一个get方法getMsg,已经不用我做过多的介绍了。

现在我们启动项目,成功后地址栏访问,http://localhost:10900/devtools/msg,结果已经拿到。

那如果我们需要修改方法呢,我们对getMsg进行了修改,然后在修改的同时,我们会看到控制台已经自动帮我们重启了。

我们再来看一下实际效果,刷新刚才的地址,可以看到,结果也发生了对应的变化。

三、xstream与devtools冲突

devtools如此方便,相信你已经迫不及待想去使用它了,但是使用devtools一点要注意一点,因为devtools是使用两个ClassLoader,一不小心,就会造成类型转换异常。

例如,当使用xstream时,这个异常就出现了,而且让人大跌眼镜。

首先我们引入xstream依赖,主要演示类型转换异常,至于xstream的使用,这里不过过多讲解。

然后编写了简单的xml解析,再简单而正确不过的代码了。

可是当我们访问它时,却意料之中的异常了,但一看异常,com.yanger.swagger2.Book不能转换为com.yanger.swagger2.Book,嗯?啥?自己没办法转成自己,顿时纳闷了。

Spring的dev-tools为了实现重新装载class自己实现了一个类加载器,来加载项目中会改变的类,方便重启时将新改动的内容更新进来,其实其中官方文档中是有做说明的:
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.

简单来说,就是要我们在resources目录下面创建META_INF文件夹,然后创建spring-devtools.properties文件,进行配置。

参考了网上的文件配置:

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

怀着激动的心情,发现并不好使。最终搜索尝试发现,如果手动指定XStream的类解析器,就不会存在转换异常,问题得到圆满解决,devtools的小船又可以愉快的划起来了。

源码地址:https://github.com/imyanger/springboot-project/tree/master/p4-springboot-devtools

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值