spring-boot+thymeleaf-multiple-template-resolvers和fallback-to-default

tcomlyy6  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(190)

我试图在我的spring boot应用程序中添加对带有thymeleaf模板的电子邮件的支持。只要我只使用存储为 .html 文件夹。我想做的是添加对使用用户配置的模板“覆盖”这些文件的支持。所以如果db中存在模板,就使用它。否则,请尝试使用文件中的。
我的配置如下:

@Configuration
public class ThymeleafConfig {

    @Bean
    public SpringTemplateEngine springTemplateEngine(DatabaseTemplateResolver databaseTemplateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        databaseTemplateResolver.setTemplateMode(TemplateMode.HTML);
        templateEngine.addTemplateResolver(databaseTemplateResolver);
        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver htmlTemplateResolver() {
        SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
        emailTemplateResolver.setPrefix("/templates/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
        emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return emailTemplateResolver;
    }

}

和数据库解析器:

@RequiredArgsConstructor
@Component
public class DatabaseTemplateResolver extends StringTemplateResolver {

    @Qualifier("htmlTemplateResolver")
    private final SpringResourceTemplateResolver htmlTemplateResolver;

    @Override
    public ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String templateName, Map<String, Object> templateResolutionAttributes) {
        model.runInTransaction(tx -> {
            Optional<Template> template = // load template from DB;

            if (template.isPresent()) {
                return super.computeTemplateResource(configuration, ownerTemplate, template.get().getContent(), templateResolutionAttributes);
            } else {
                return htmlTemplateResolver.resolveTemplate(configuration, ownerTemplate, templateName, templateResolutionAttributes);
            }
        }, TransactionDescriptor.asSystemUser());

        return null;
    }

}

在这里的db中找到模板并返回,但我得到以下错误:

[THYMELEAF][task-2] Exception processing template "email-notification": Error resolving template [email-notification], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [email-notification], template might not exist or might not be accessible by any of the configured Template Resolvers
    at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:869)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:607)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1059)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1048)

有人知道我做错了什么吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题