springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker

1、自己搭建了一个springboot 的小项目,同时用到了thymeleaf和freemarker 两种视图。

默认情况下,freemarker视图优先级会高于thymeleaf 。  所有生成视图时会优先生成 freemarker的视图

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker

然后想着是不是可以在配置文件里面修改order,但是配置貌似无效,视图解析器加载后都成了这个默认值springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker

  下图中的spring.thymeleaf.template-resolver-order并没有生效。

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarkerspringboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker


2、于是重新定义一个thymeleaf视图解析器Bean,并设置order 为1

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarkerspringboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker


然后自定义的视图解析器的确排到第一位了,order也为我设置的1.

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker

但是又出现了一个新的问题。thymeleafViewResolver  解析视图名时,即使视图文件不存在,依然会返还一个View 视图对象。

这就造成了freemarker视图解析器永远不会使用。

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarkerspringboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker


3、解决方法,新写一个MyThymeleafViewResolver 继承于ThymeleafViewResolver,

然后重写loadView方法,判断视图文件是否存在,如果不存在,就返回null,

这样在DispatcherServlet # resolveViewName方法中就会去寻找下一个视图解析器(FreeMarkerViewResolver)进行解析。

springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker


springboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarkerspringboot下面thymeleaf和freemarker两种共存,并且设置thymeleaf的优先级高于freemarker