0
votes

It is a spring boot project and the web page is rendered by Thymeleaf. When I put spring-boot-starter-thymeleaf in the pom.xml and start the applicaiton, it is trying to find all the beans which implements ViewResolver in its container. And you see here it find thymeleafViewResolver.

I am just curious that when and how does Spring boot put this ThymeleafViewResolver class into its bean container?

enter image description here

1

1 Answers

2
votes

It is due to SpringBoot auto-configuration feature which will automatically create a bean dynamically based on different conditions such as if a library can be found from the class paths, or if developers already define a bean of certain type etc...

If you turn on the debug mode by putting debug=true in the application.properties , it will print out a report during application startup saying which beans are auto created due to which conditions.

In the example of the spring-boot-starter-thymeleaf , you can find the following from the report :

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

And by tracing the source codes of ThymeleafViewResolverConfiguration :

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

You could find out thymeleafViewResolver is in a type of ThymeleafViewResolver and @ConditionalOnMissingBean here means that this bean will only be created if there is no bean of the ThymeleafViewResolver type is defined yet.