Monday, March 4, 2013

Working with Spring 3.

Dear All,
Staring with Spring 3, The Spring API needs to included in the project, please download Spring 3 Framework libraries and add to the referenced libraries of project.



Create JAVA project with following structure,

    

In Spring, spring configuration file acts as a controller of the application,
here we created the "Spring3HelloWorld.xml" as a spring controller, which include the bean tag followed by root tag which might be contains multiple bean references, for example now we are including only tow beans as a refernce,
Here the same bean id associated with the bean class.

Spring3HelloWorld.xml
 
Now we created two beans,
Spring3HelloWorld.java
package spring.com;

public class Spring3HelloWorld {
   
    public void sayHello(){
        System.out.println("Hello Spring 3.0");
    }
}

and

Spring3GoingToHell.java
package spring.com;

public class Spring3GoingToHell {
    public void sayHello1(){
        System.out.println("Going To Hell");
    }
}

Now we have the Main class calling the beans through spring framework using application context,

Spring3HelloWorldTest.java
package spring.com;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

public class Spring3HelloWorldTest {

    public static void main(String[] args) {

        //way 1
        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("Spring3HelloWorld.xml"));

        //way 2
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring3HelloWorld.xml");

        //way 3
        ApplicationContext context1 = new GenericXmlApplicationContext("Spring3HelloWorld.xml");
       
       
       
        Spring3HelloWorld myBean0 = (Spring3HelloWorld)beanFactory.getBean("Spring3HelloWorldBean");
        myBean0.sayHello();
       
        Spring3GoingToHell myBean1 = (Spring3GoingToHell) context.getBean("Spring3GoingToHellBean");
        myBean1.sayHello1();
       
        Spring3HelloWorld myBean2 = (Spring3HelloWorld) context1.getBean("Spring3HelloWorldBean");
        myBean2.sayHello();
  
    }
}     

Here are three ways to get a bean object from the Spring configuration xml file, Just get the object of bean from application context and then invoke the bean related operations.

For more details or any queries please mail me at
amol.phasale@gmail.com 

Thank you.

Followers