Thursday 17 March 2011

Loading beans from a bean descriptor XML file in spring

Consider a java class:
package com.vaani.spring.beans;
class Greeting{
    public Greeting() {
System.out.println(
"Hello");
}
}

Bean Descriptor file
Now consider the bean descriptor file , we can create a file simply like this:

<beans>
<bean id="greetingID" class="com.vaani.spring.Greeting"/>
</beans>


In this example,class “com.vaani.spring.GreetingService” is registered in Spring under name "greetingService".

Now once the descriptor for this bean is written, we can use this bean in any file that needs it.

Example see the main method here:

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {

ApplicationContext context =
 
                new ClassPathXmlApplicationContext("beans.xml");
Greeting greeting= 
                (Greeting)context.getBean("greetingID");

}
}
So we use getBeans method to get the bean by ID.
 Points to be noted areSuppose if the package name is com.vaani, than we can give path of the beans file in many ways. Have a look at these:
  • If we say:
    ClassPathXmlApplicationContext("beans.xml");
    Than it means it looks into the folder the main file is for beans.xml.
  • if we say
    ClassPathXmlApplicationContext("/com/vaani/beans.xml");
    It is same as
    ClassPathXmlApplicationContext
    (
    "classpath:/com/vaani/beans.xml");
Also see
Further you can load beans lazily or pre loading can be done. See here for that.
Not only this when you are testing your code using JUnit, you can give bean file path via annotations, which is very handy. See here for this.

No comments:

Post a Comment