Springboot中@Autowired为何获取了我们没有注入的Bean?
在做仿牛客网项目的时候,有这样一段话:
@Autowired
private TemplateEngine templateEngine;
在写到这里的时候我很疑惑,我自己明明没有手动注入这个类,为何能够通过@Autowired进行自动装配?
我有从头检查到尾,发现的确没有将该类给IOC容器管理。于是我怀疑是springboot启动的时候将该类自动交给了IOC容器进行管理,但是我没有证据。
于是我踏上了漫长的查找自动装配的原因的过程…
在经过很长时间的寻找后,我终于确定是springboot在启动的时候将该类自动交给了IOC容器进行管理。
在springboot入口处加入以下代码
@SpringBootApplication
public class CommunityApplication {
public static void main(String[] args) {
SpringApplication.run(CommunityApplication.class, args);
}
/**
* 项目启动之前,预先加载数据。比如,权限容器、特殊用户数据等。通常我们可以使用监听器、事件来操作。
* 但是,springboot提供了一个简单的方式来实现此类需求,即,CommandLineRunner。
* Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。
* 也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。@Order(value=1)
* @author Sepnine
* @date: 2022/9/14 18:36
*/
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("项目启动,正在加载数据...");
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
重新启动项目
发现springboot在启动的时候就已经将该类给了IOC容器,除此之外还将很多Bean交给了IOC容器。