SpringBoot如何将Thymeleaf视图解析器放入其bean容器中

SpringBoot如何将Thymeleaf视图解析器放入其bean容器中,spring,spring-boot,spring-mvc,thymeleaf,Spring,Spring Boot,Spring Mvc,Thymeleaf,这是一个spring启动项目,网页由Thymeleaf呈现。当我将spring boot starter thymeleaf放入pom.xml中并启动应用程序时,它正试图在其容器中找到实现ViewResolver的所有bean。你看这里它找到了thymeleafViewResolver 我只是好奇,SpringBoot何时以及如何将这个ThymeleafViewResolver类放入它的bean容器中 这是由于SpringBoot特性,它将根据诸如是否可以从类路径中找到库,或者是否开发人员已经定

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

我只是好奇,SpringBoot何时以及如何将这个ThymeleafViewResolver类放入它的bean容器中

这是由于SpringBoot特性,它将根据诸如是否可以从类路径中找到库,或者是否开发人员已经定义了某种类型的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;
}
您可以发现
thymeleafviewsolver
属于
thymeleafviewsolver
的一种类型,这意味着只有在没有定义
thymeleafviewsolver
类型的bean的情况下才会创建这个bean。

这是由于SpringBoot特性,它会根据这些bean动态地创建一个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;
}

您可以发现
thymeleafviewsolver
的类型为
thymeleafviewsolver
,这意味着只有在没有定义
thymeleafviewsolver
类型的bean时,才会创建此bean。

非常感谢。我用谷歌搜索了很多网页来研究自动配置。真的很酷!在你的帖子中,你指的是哪个版本的自动配置?ThymeleafViewResolverConfiguration的内容与我的版本(spring-boot-autoconfigure-1.5.17.RELEASE.jar)有点不同。我使用的是2.1.X版本,但想法是一样的。非常感谢。我用谷歌搜索了很多网页来研究自动配置。真的很酷!在你的帖子中,你指的是哪个版本的自动配置?ThymeleafViewResolveConfiguration的内容与我的版本(spring-boot-autoconfigure-1.5.17.RELEASE.jar)有点不同,我使用的是2.1.X版本,但想法是一样的。