Spring Boot Thymeleaf 配置多个模版路径

Spring Boot Thymeleaf About 2,143 words

默认配置

从源码可知,默认会注入一个defaultTemplateResolver对象,我们也可以注入同名对象起到覆盖作用。

@AutoConfiguration(after = { WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@Import({ TemplateEngineConfigurations.ReactiveTemplateEngineConfiguration.class,
        TemplateEngineConfigurations.DefaultTemplateEngineConfiguration.class })
public class ThymeleafAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnMissingBean(name = "defaultTemplateResolver")
    static class DefaultTemplateResolverConfiguration {
        @Bean
        SpringResourceTemplateResolver defaultTemplateResolver() {
            // ...

        }
    }
}

新增路径

注入不同名称的SpringResourceTemplateResolver即可。

还可以不同的ITemplateResolver实现类来映射对应的文件夹。

@Configuration
public class Config {

    private final ThymeleafProperties properties;
    private final ApplicationContext applicationContext;

    Config(ThymeleafProperties properties, ApplicationContext applicationContext) {
        this.properties = properties;
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver secondTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(this.applicationContext);
        resolver.setPrefix("file:" + System.getProperty("user.dir") + "/templates2/");
        resolver.setSuffix(this.properties.getSuffix());
        resolver.setTemplateMode(this.properties.getMode());
        if (this.properties.getEncoding() != null) {
            resolver.setCharacterEncoding(this.properties.getEncoding().name());
        }
        resolver.setCacheable(this.properties.isCache());
        Integer order = this.properties.getTemplateResolverOrder();
        if (order != null) {
            resolver.setOrder(order);
        }
        resolver.setCheckExistence(this.properties.isCheckTemplate());
        resolver.setCacheTTLMs(Duration.ofSeconds(5).toMillis());
        return resolver;
    }
}
Views: 1,121 · Posted: 2023-08-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh