Arun Raaj Arun Raaj - 1 year ago 114
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");

Hello h2= new Hello(); //if i write this

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

by doing

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

Answer Source

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.


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

and it is creating object of Hello class by using xml

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download