我是Spring的初学者,在理解这两个如何工作时遇到了问题。我将通过示例解决我的问题。
我们有一个带有Spring Core模块的项目,在这个项目中,我们有两个类,它们在不同的程序包中用@Component
注释,而在三个程序包中的一个主类。
现在,我们创建三个不同的@Configuration
类,在其中一个上我们指定@ComponentScan(package with first @Component annotated class)
将其命名为config1,在几秒钟内,我们指定@ComponentScan(package with second @Component annotated class)
将其命名为config2,然后在第三次我们指定{{1 }}命名为config3。
现在在主类中,我们有以下代码:
@ComponentScan(both packages)
我的理解:
在第一点,我们的应用程序运行了Spring Core。此时,Spring创建了Container,它没有对象。它是空的。 Point 1 in time
因此,我们创建了public static void main(String[] args) {
// point 1 in time
System.out.println("lalalalalala");
// point 2 in time
AnnotationConfigApplicationContext context1 =
new AnnotationConfigApplicationContext(config1.class);
// point 3 in time
AnnotationConfigApplicationContext context2 =
new AnnotationConfigApplicationContext(config2.class);
// point 4 in time
AnnotationConfigApplicationContext context3 =
new AnnotationConfigApplicationContext(config3.class);
}
类型的对象。我们将config1类作为参数发送给该对象。然后,该对象将读取AnnotationConfigApplicationContext
批注并扫描POJO和元数据。扫描之后,@ComponentScan
对象将创建bean(在此示例中为1 bean,并希望通过这种类型的上下文加载它)并将其放置在Spring Container中。因此,在我们的应用程序中,这是我们第一次在Spring容器中添加一些东西。
point 2 in time
类型AnnotationConfigApplicationContext
的对象将仅引用我们放入Container ?!中的bean。因此,当我们调用AnnotationConfigApplicationContext
方法时,我们的上下文将从容器中“带来” bean吗?
point 3 in time和point 4 in time ...发生同样的事情
因此,基本上,我的问题是:对象是getBean()
的某种实现,读取POJO和元数据,创建BEANS并将其放置到Spring Container中?它不保存bean,仅指向Container中的那些bean?而且Container只包含那些bean,除了保存bean之外,他没有其他功能,例如它仅在内存中的位置?而且我们的应用程序中只有一个Container,我们可以有多个BeanFactory对象,但只有一个Container?