【问题标题】:How does Spring boot put Thymeleaf view resolver into its bean containerSpring boot 如何将 Thymeleaf 视图解析器放入其 bean 容器中
【发布时间】:2019-10-24 12:42:52
【问题描述】:

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

我只是好奇 Spring boot 何时以及如何将这个 ThymeleafViewResolver 类放入其 bean 容器中?

【问题讨论】:

    标签: spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    这是由于 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。

    【讨论】:

    • 非常感谢。我搜索了很多页面来研究自动配置。真的很酷!
    • 对于您的帖子,您指的是哪个版本的自动配置? ThymeleafViewResolverConfiguration 的内容和我的版本有点不同,是spring-boot-autoconfigure-1.5.17.RELEASE.jar
    • 我用的是2.1.X版本但是思路是一样的。
    猜你喜欢
    • 2016-01-27
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2019-11-04
    • 1970-01-01
    • 2019-06-11
    • 2017-02-02
    相关资源
    最近更新 更多