Thursday 14 April 2016

HelloWorld : Basic example of Spring Framework

Hi Folks !!

After a long time coming back to blog !!! Hope you are still in touch with Spring Framework. For all those who are waiting for the first implementation of Spring .. Here I am !!

We had enough theory earlier about what is dependency injection and why dependency enjoy. Lets make our hands wet with some coding now.

HelloWorld Implementation . 

In this implementation we will learn the property injection using spring framework.

To begin with create a bean, MyBean

public class MyBean {

             private String message;

             public void setMessage(String message)
             {
                      this.message = message;
             }

             public void show()
             {
                      System.out.println(message);
             }


}

As you can observer, MyBean has a property message, and setter, getter methods for the same. Normaly we would have gone with constructor arguments to initiate the message like :

MyBean mb=new MyBean("My message"); 

But to implement dependency injection we will be injecting this property through xml.

Create a xml file, config.xml in src folder :

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="id1" class="MyBean">

<property name="message" value="Welcome to spring" />

</bean>

</beans>

Here object of bean MyBean is referred by bean is "id1". The property tag contains attributes name and values which is used to push the values of properties for "id1".

Create application class to load the object from bean container:

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

public class MainApp {

          public static void main(String[] args)
          {
                   Resource res = new ClassPathResource("config.xml");
                   BeanFactory factory = new XmlBeanFactory(res);

                   Object o = factory.getBean("id1");
                   MyBean wb = (MyBean)o;

                   wb.show();

          }

}

Thats it guys !! You are ready to execute your first spring application. 

Execute MainApp class and you will get output as : 

Welcome to spring

Jar files required to run this application;
1. spring-2.5.jar
2. common-logging-1.1.jar
3. cgilib-2.2.jar


In my coming post I will explain how to push object through dependency injection and pushing the properties through constructor argument.. 

Keep reading  :-)




No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...