前言

本文是基于江南一点雨的 Spring Boot+Vue 系列视频教程第 三 章的第三节,详情参考Spring Boot+Vue系列视频教程 在观看学习这一节时,发现当进行手动渲染 Thymeleaf 模板时,通过 @Autowired 注解来对 TemplateEngine 进行自动装配时,发现 idea 对其显示 No beans of 'TemplateEngine ' type of found。 idea中显示如下: 错误显示如下

但是当我运行后,没有报错,成功的运行了。于是勾引了我的好奇心。猜测是springboot启动时,容器中才有Bean,没启动前,容器中没有。

验证猜测

于是为了验证猜测是否正确,开启了漫长的寻找之路。虽然过程不及十万八千里,但也差不多。没办法本人菜鸡一个。 1、首先,自己想的是能不能通过 idea 的 debug 来查看。最后发现自己不能做到,无从下手,感觉很烦。 2、于是开启了面向百度编程,查找看看有没有捷径:即通过某种方法/技术来实现,例如监听器。嘿嘿,你猜怎么着,还真有。那就是通过 CommandLineRunner 接口

首先看 CommandLineRunner 是什么?

它是springboot提供的为了解决这样的需求,什么样的需求呢?就是在springboot启动时加载一些数据或预先完成某些动作 且Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例。 所以接下来上代码:

@SpringBootApplication
public class ThymeleafApplication {
    @Autowired
    TemplateEngine templateEngine;

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafApplication.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx){
        return args -> {
            System.out.println("springboot启动前.....");
            String[] names = ctx.getBeanDefinitionNames();
            for (String name : names) {
                if(name.contains("templateEngine")) System.out.println(name);
                else continue;
            }
        };
    }
}

结果如下: 结果如下 结果如下

最后即验证了猜测。

作者:|xashould|,原文链接: https://www.cnblogs.com/xiarongblogs/p/17369940.html

文章推荐

itextpdf5.5.13给pdf添加图片水印、添加文字水印(平铺)、...

vue自定义组件——search-box

深入理解 python 虚拟机:字节码教程(1)——原来装饰器是这样...

内存管理:判断对象是否存活

asp.net 应用程序中同步方法调用异步方法无响应解决方法

Cesium官方教程——Fabric

2023-03-15 用Node.js开发一个http代理服务器

在Java中,使用HttpUtils实现发送HTTP请求

Linux进程与线程的基本概念及区别

c语言for循环语句的运用

与NewBing一起写作:《Web应用安全入门》

consul系列文章02---替换掉.netcore的配置文件