Spring Boot如何将Thymeleaf视图解析器放入其bean容器

时间:2019-06-10 05:24:37

标签: spring spring-boot spring-mvc thymeleaf

这是一个春季启动项目,网页由Thymeleaf呈现。当我将spring-boot-starter-thymeleaf放入pom.xml并启动应用程序时,它正在尝试查找在其容器中实现ViewResolver的所有bean。您会在这里看到thymeleafViewResolver。

我很好奇,Spring引导何时以及如何将ThymeleafViewResolver类放入其bean容器中?

enter image description here

1 个答案:

答案 0 :(得分:2)

这是由于SpringBoot的auto-configuration功能将基于different conditions自动动态创建一个bean,例如是否可以从类路径中找到库,或者开发人员是否已经定义了特定的bean。键入等等...

如果通过将debug=true放在application.properties中来打开调试模式,它将在应用程序启动期间打印出一份报告,指出由于哪些条件而自动创建了哪些bean。

spring-boot-starter-thymeleaf的示例中,您可以从报告中找到以下内容:

ThymeleafAutoConfiguration.ThymeleafWebMvcConfiguration.ThymeleafViewResolverConfiguration#thymeleafViewResolver matched:
                  - @ConditionalOnMissingBean (names: thymeleafViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition)

并通过跟踪ThymeleafViewResolverConfiguration的源代码:

@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(this.templateEngine);
    resolver.setCharacterEncoding(this.properties.getEncoding().name());
    //.......   
    return resolver;
}

您可能会发现thymeleafViewResolver的类型为ThymeleafViewResolver@ConditionalOnMissingBean,这意味着仅当没有ThymeleafViewResolver类型的bean时才会创建此bean。已经定义。