Friday, March 18, 2011

Loading beans from a bean descriptor XML file in spring

Consider a java class:
package com.vaani.spring.beans;
class Greeting{
    public Greeting() {

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

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

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;
public class Main {
    public static void main(String[] args) {

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

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:
    Than it means it looks into the folder the main file is for beans.xml.
  • if we say
    It is same as
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