在SpringBoot中同时使用enjoy模板引擎和devtools进行热部署时,会发生冲突(enjoy模板引擎使用了Shared Method扩展的情况才会发生)报以下错误。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jFinalViewResolver' defined in class path resource [com/example/demo/config/EnjoyConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.jfinal.template.ext.spring.JFinalViewResolver]: Factory method 'jFinalViewResolver' threw exception; nested exception is java.lang.RuntimeException: The shared method is already exists : com.example.demo.config.EnjoySharedMethod.test()
关键错误
The shared method is already exists : com.example.demo.config.EnjoySharedMethod.test()
为了明确错误的原因,我们先了解下spring-boot-devtools实现热部署的原理:SpringBoot热部署工具spring-boot-devtools原理
所以我们对enjoy进行配置的方法
@Bean public JFinalViewResolver jFinalViewResolver() { JFinalViewResolver jfr = new JFinalViewResolver(); //项目在开发环境下则开启视图的开发模式 if (profileConfig.isDev()){ jfr.setDevMode(true); } //视图中访问session中的内容 jfr.setSessionInView(true); ClassPathSourceFactory classPathSourceFactory = new ClassPathSourceFactory(); jfr.setSourceFactory(classPathSourceFactory); jfr.setOrder(0); jfr.setContentType("text/html;charset=UTF-8"); //指定默认的日期格式化样式 jfr.setDatePattern("yyyy-MM-dd HH:mm:ss"); //指定模板文件存放位置 jfr.setBaseTemplatePath("/templates/"); //添加SharedMethod的类 jfr.addSharedMethod(new EnjoySharedMethod()); return jfr; }
会被重新执行,也就是jfr.addSharedMethod(new EnjoySharedMethod());这个方法在每一次热部署的时候都会被重复执行。跟踪方法发现,该方法是继续调用的engine.addSharedMethod(sharedMethodFromObject);而engine这个对象是JFinalViewResolver这个类的静态属性static final类型。但是由于JFinalViewResolver属于第三方jar包,所以这个类相关的东西并不会重新加载,即enjoy中已经有了我们的SharedMethod扩展方法配置。
综上原因,从而导致了出现The shared method is already exists错误。
那么如何解决这个问题呢?有一个办法就是,我们将enjoy相关的代码也让其在热部署的时候重新加载。具体的操作方法如下:
1、在resources目录下新建META-INF目录
2、在META-INF目录下新建文件spring-devtools.properties,文件内容如下:
restart.include.enjoy=/enjoy-[\\w\\W]+.jar
完成。上述的[\\w\\W]+的含义是使用了正则,这里匹配了enjoy的版本号。
完整代码:https://gitee.com/lqccan/blog-demo demo9