这是一个春季启动项目,网页由Thymeleaf呈现。当我将spring-boot-starter-thymeleaf放入pom.xml并启动应用程序时,它正在尝试查找在其容器中实现ViewResolver的所有bean。您会在这里看到thymeleafViewResolver。
我很好奇,Spring引导何时以及如何将ThymeleafViewResolver类放入其bean容器中?
答案 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。已经定义。