Search This Blog

Saturday 4 February 2012

A Simple Spring Program

In this post, I shall attempt to create a simple bean using spring.
Task:
A main program that will display the Hello World Message
Solution:
Step 1: Create the java "service" that generates the Message.
Te below java class executes the "complex" code that generates the Hello World message
package com.start;

public class HelloWorldMessanger {

    public String getMessage() {
        return "Hello World";
    }
}
Step 2: Provide information about this service to the Spring Container.
The Spring Container is responsible for instantiating our beans providing it to our code. For this the most common way is to use a xml based configuration. Our xml file is as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="messager" class="com.start.HelloWorldMessanger" />

</beans>
Step 3: Create the client code to execute the service.
package com.runner;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.start.HelloWorldMessanger;

public class Client {

    public static void main(String[] args) {
        Resource res = new ClassPathResource("beans.xml");
        XmlBeanFactory beanFactory = new XmlBeanFactory(res);
        HelloWorldMessanger messager = (HelloWorldMessanger) beanFactory.getBean("messager");
        System.out.println(messager.getMessage());
    }
}
The ClassPathResource is used to load the xml file from the program class path. The XmlBeanFactory is the SpringContainer which will load and instantiate our Messenger class. Our client program is not aware of the logic involved in creation of the messanger object. It is assured that all the creation pains will be handled by the BeanFactory. The Client can go ahead and confidently print the appropriate message on the screen.
This completes our coding part of the solution.
Step 4: Add the relevant jars for executing the above code.
For the above code to compile and run we need to add relevant spring jars. Below is a snapshot of my class path from eclipse:
This completes the setup to be done The code is now ready for execution. On running the client code we now see the output as below
Feb 4, 2012 10:16:53 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Hello World

No comments:

Post a Comment