关于在 springboot 中使用 @Autowired 注解来对 TemplateEngine 进行自动装配时,无法注入的问题。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

前言

本文是基于江南一点雨的 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;
}
};
}
}

结果如下:



最后即验证了猜测。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring