getBean() 方法在这里做什么?

What does getBean() method do here?

getBean() 方法在这里做什么,它在程序中如何工作?

ApplicationContext aplicntxt = new 
ClassPathXmlApplicationContext("springconfig.xml");  

Hello h = (Hello) aplicntxt.getBean("springconfig.xml");  
h.display();

Hello h2 = new Hello();  //if I write this
h2.display();  

我的问题是为什么h2.display通过springconfig.xml检索空值而h.display检索存储值?

请告诉我

ApplicationContext aplicntxt = new ClassPathXmlApplicationContext("springconfig.xml");

先做?

xml 文件的所有值是否都存储到第一步的 pojo class 设置器中?

然后我们将值存储到一个对象中h 通过

Hello h = (Hello) aplicntxt.getBean("springconfig.xml");

你的问题本质上是 "How does spring work",official documentation

以下创建由 springconfig.xml 定义的所有 bean,即它创建给定类型的对象,并注入您定义的任何属性,具体取决于您的具体配置,它还可能执行类似的操作包扫描、注解处理等

ApplicationContext aplicntxt= new ClassPathXmlApplicationContext("springconfig.xml");

XML

<bean class="org.example.Hello" id="foo" />
<bean class="org.example.Hello" id="bar" />

这将创建一个类型为 Hello 的对象并用 ID "foo" 和 "bar"

标记它们

所有 bean 都根据它们的 ID 存储,以便以后通过 getBean() 检索,请注意,这采用 bean ID 或名称,而不是 XML 文件。

Hello h = (Hello) aplicntxt.getBean("foo");

从快速查看来看,这段代码似乎使用 spring 用 xml 文件中找到的 spring bean 中指定的值初始化 Hello 对象(我我假设这就是 filr 中的内容,但如果你 post 它我可以更具体)。当你创建第二个 hello 对象时,你正在使用构造函数的默认显示值,即 null。

From spring doc

接口org.springframework.context.ApplicationContext表示Spring IoC容器,负责实例化、配置和组装上述bean。容器通过读取配置元数据获取有关要实例化、配置和 assemble 哪些对象的说明。配置元数据以 XML, Java annotations, or Java code. 表示,它允许您表达组成应用程序的对象以及这些对象之间丰富的相互依赖关系。

ApplicationContext interface 的多个实现与 Spring 一起开箱即用。在独立应用程序中,通常创建 ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. 的实例,而 XML 一直是定义配置元数据的传统格式,您可以指示容器使用 Java 注释或代码作为元数据格式通过向 declaratively 提供少量 XML 配置,启用对这些额外元数据格式的支持。

现在你的问题及其简单的 ApplicationContext 激活对象(它是急切的容器)并查找声明的 beans 以便在调用时加载对象。

现在考虑如果您有两个 bean,并且您需要其中一个,您将通过使用 ctx.getBean("beanId") 加载实例并提供用此 bean 声明的数据来找到那个 bean,其中 beanId 会告诉反对 load.

考虑以下示例

<bean id="a" class="package.Hello" /> //here it will look for bean name and then loads the class

现在当你这样称呼它时

ApplicationContext ctx=new ClassPathXMLApplicationContext("configuration.xml");

//will look for configuration.xml bean file if it is not in path then throw execption.

现在

Hello hello=ctx.getBean("a");

// if configuration.xml contains any bean named "a" and holds reference to class(hello) load it immediately and return object of that class

相同
Hello hello=new Hello();
hello.method();

它正在使用 xml

创建 Hello class 的对象

您在代码中所做的称为 Spring Dependency Injection,它允许您定义应用程序 bean 并在需要时注入它们。就像您在代码中使用的 getBean() 方法,它从 XML 文件中注入特定的 bean。