2016-07-16 106 views
1

在這裏做的getbean()方法是什麼,它在程序中是如何工作的?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檢索空值,h.display通過springconfig.xml檢索存儲的值?

請告訴我這是什麼

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

先做什麼?

第一步是否將所有xml文件的值存儲到pojo類setter?

然後我們做

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

所有你需要的只是開始學習春天http://www.tutorialspoint.com/spring/ – tinku

+0

我想知道內部流量,這是不是提供的任何地方...我想知道這裏發生了什麼步驟一步一步.. 只有兩行代碼....請告訴我流程....謝謝。 –

回答

1

From spring doc

接口org.springframework.context.ApplicationContext表示Spring IoC容器和負責實例,配置和組裝在上述豆類。容器通過讀取配置元數據獲取有關要實例化,配置和組裝的對象的指示信息。配置元數據在XML, Java annotations, or Java code.中表示。它允許您表示組成應用程序的對象以及這些對象之間豐富的相關性。

ApplicationContext interface的幾個實現是隨Spring一起提供的。在獨立應用程序中,通常創建ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.的實例雖然XML是用於定義配置元數據的傳統格式,但您可以通過向容器提供少量XML配置來指示容器使用Java註釋或代碼作爲元數據格式啓用支持爲這些額外的元數據格式。

現在您的問題和它的簡單ApplicationContext激活對象(它是渴望的容器)並尋找beans聲明,以便每次調用時加載對象。

現在考慮,如果你有兩個豆,你需要他們中的一個,您將使用ctx.getBean("beanId")加載實例發現,豆,並提供與這個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

+0

好的。所以加載對象,現在當我調用「h.display()」時,是訪問xml文件還是調用Hello類的方法? –

+0

@ArunRaaj我編輯我的答案 – emotionlessbananas

+0

我希望它會幫助你 – emotionlessbananas

3

你的問題基本上是「如何做春天的工作」,這是廣泛被official documentation

覆蓋下面創建的所有存儲的值對象h 由springconfig.xml定義的bean,它創建給定類型的對象,並注入你定義的任何屬性,具體取決於你的確切配置,它也可以做像包掃描,註釋處理等事情。

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

XML

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

這將創建一個類型爲你好的對象,並與ID爲「foo」和「酒吧」

所有的豆類都存儲對它們的ID爲以後的檢索標記它們通過getBean(),請注意這取決於bean的ID或名稱,而不是XML文件。

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

感謝亞當,那麼「獲取豆」的確切含義是什麼? 所有的值已經存儲在Hello類中,然後我們通過'h.display()'檢索它們? –

+0

獲取bean =>通過註冊表中的ID,映射內存中的故事,查找bean,將其稱爲您想要的內容。這可能是一個HashMap的底線.. – Adam

+0

Thanks____________ –

1

從這個快看,似乎這個代碼使用彈簧來初始化在XML文件中找到的春天豆(我假設這是什麼在filr,但指定的值Hello對象如果你發佈它,我可以更具體)。當你創建第二個hello對象時,你正在使用構造函數的默認值進行顯示,它是空的。

+0

Thanks____________ –

1

你在做什麼的代碼被稱爲Spring Dependency Injection這讓你定義應用程序豆,當你需要將它們注入創造Hello類的對象。像getBean()方法,您可以在代碼中使用它從XML文件注入特定的bean。

+0

謝謝____________ –

+0

你應該使用+1這意味着感謝您在stackovewrflow有用的答案!祝你好運!! –