Arun Raaj Arun Raaj - 4 months ago 13
Java Question

What does getBean() method do here?

What is the getbean() method doing here and how does it work in a program?

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();


My question is why h2.display retrieves null value and h.display retrieves the stored values through springconfig.xml?

Please tell me what does

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


do first?

Are all the values of xml file stored to the pojo class setters at first step?

Then we are storing the values to an object
h

by doing

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

Answer

From spring doc

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It allows you to express the objects that compose your application and the rich interdependencies between such objects.

Several implementations of the ApplicationContext interface are supplied out-of-the-box with Spring. In standalone applications it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has been the traditional format for defining configuration metadata you can instruct the container to use Java annotations or code as the metadata format by providing a small amount of XML configuration to declarativelyenable support for these additional metadata formats.

Now Your Question and its simple

ApplicationContext activates the object(it is eager container) and looks for the beans declared so the objects are loaded whenever it is called.

Now consider if you have two beans , and you need one of them you will find that bean by using ctx.getBean("beanId") to load instance and to provide data declared with this bean where beanId will tell which object to load.

consider following example

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

Now when You call it like

`

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

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


now 

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

is same as 

Hello hello=new Hello();`
hello.method();

and it is creating object of Hello class by using xml

Comments