Sunday, March 3, 2013

Getting started with Spring

There are only three simple steps to do it. Let's see a simple example on how to start with Spring.

1. Create a bean class, beans are nothing but simple POJOs.

package com.myexamples.spring;
class Student
      private String name;
      public String getName()
           return name;
      public void setName(String name)
  = name;

2. Create bean configuration file - spring-context.xml
<beans xmlns=""
 <bean id="studentBean" class="com.myexamples.spring.Student">
  <property name="name" value="John" />
In spring-context.xml, we have defined one bean which is a plain pojo and passing an argument to it named "name"

3. Create the Application, which invokes the Bean
class MainClass
      public static void main(String...args)
           ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    Student std = (Student)context.getBean("studentBean");
MainClass is the actual application, which access the bean using ApplicationContext.

Steps to access the bean from Application Context

  1. Get an Instance of ApplicationContext, there are many types to get it. Here am using XmlApplicationContext.
  2. Get the bean from the context using getBean method. The beans created by Spring are by default singleton. So if an instance of studentBean exists then created otherwise returns the same instance again. While creating the instance, spring initializes with the properties mentioned in the context xml file (spring-context.xml in this case)
  3. Now if you print, getName(), it will print "John" on the console