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)
      {
           this.name = name;
      }
}

2. Create bean configuration file - spring-context.xml
<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-2.5.xsd">
 
 <bean id="studentBean" class="com.myexamples.spring.Student">
  <property name="name" value="John" />
 </bean>
</beans>
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");
    System.out.println(std.getName());
      }
}
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

No comments:

Post a Comment