Wednesday, 11 May 2011

Spring example 2 program

Prerequisite:

    Java SDK 1.6 (Used during this tutorial)
    Eclipse Indigo (Can also be used Later versions)
    Spring Framework 3.1
 
  Spring Environment Set up

Application to be Developed :



Here in this tutorial we are developing an application where we will Insert(Create) User Details in System. Other CRUD operation look here.
Application Setup :
How to create a Project in Eclipse?

Create the Java Project
Give the project name: SpringExample
Finish

Step 2: Create the package:
under the src folder in the created project.
Go to src Folder
right click the mouse
click on package



re



Add required Spring libraries using Add External JARs option
Create Java classes HelloWorld and MainApp under the com.rajendra package.



Create Beans configuration file Beans.xml under the src folder.
The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.



HelloWorld.java

package com.rajendra;

public class HelloWorld {
 private String message;
 public void setMessage(String message){
this.message=message;
 }
 public void getMessage(){
System.out.println("your message : "+message);
 }
}

MainApp.java

package com.rajendra;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] args){
@SuppressWarnings("resource")
ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA=(HelloWorld)context.getBean("helloWorld");
objA.setMessage("This is Object A");
objA.getMessage();
HelloWorld objB=(HelloWorld) context.getBean("helloWorld");
objB.getMessage();
}

}

Following is the configuration file Beans.xml required for singleton scope:

<?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="helloWorld" class="com.rajendra.HelloWorld"
      scope="singleton">
   </bean>

</beans>


Once you are done with creating source and bean configuration files, let us run the application.

Output:

your message : This is Object A
your message : This is Object A


No comments:

Post a Comment