Spring Boot中Thymeleaf引擎動態刷新

在Spring 項目中使用thymeleaf引擎,能夠很好地解決部署問題,不用再導出jsp文件。真正作到一個jar包便可發佈。但Thymeleaf有個缺陷:必須重啓工程才能刷新。其實把配置稍微改一下,就能夠在開發的時候動態刷新。html

@Configuration
@EnableWebMvc
public class ThymeleafConfig extends WebMvcAutoConfiguration {
    @Autowired
    ApplicationContext applicationContext;

    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        viewResolver.setCache(false);
        return viewResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        URL resource = this.getClass().getClassLoader().getResource("templates/");        //這裏把系統獲取到的Class的path替換爲源碼對應的Path,這樣修改的時候就能夠動態刷新
        String devResource = resource.getFile().toString().replaceAll("target/classes", "src/main/resources");
        resolver.setPrefix("file:"+devResource);        //不容許緩存
        resolver.setCacheable(false);
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
}
相關文章
相關標籤/搜索