【发布时间】:2020-11-20 09:11:12
【问题描述】:
Spring会自动实例化ApplicationContext吗?
如果我的 bean 是这样定义的
@Component
public class Car{
...
}
然后我有我的配置类,它通过注解 @ComponentScan 告诉 Spring 容器在哪里寻找 bean
@Configuration
@ComponentScan
public class AppConfig {
...
}
Spring 是否会自动创建一个上下文来加载我所有的 bean?还是我必须以编程方式创建它?如果是这样,我该怎么做?
@Configuration
@ComponentScan
public class AppConfig {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
context.getBean(Car.class);
...
}
即使这样做,也可能会出现问题,因为每次我需要上下文时,我都必须调用 new AnnotationConfigApplicationContext... 实例化上下文并使他在整个项目中可用的推荐方法是什么,可能作为 Spring Boot 应用程序中的一个 bean,我可以在其中自动装配它。
Spring Boot 如何初始化它,加载所有 bean 并让上下文作为 bean 可用,准备好自动装配?
【问题讨论】:
标签: spring spring-boot applicationcontext