First Time Spring

Very first time in Spring, this is the right place!

Objectives

  • How to code your first Spring java application?
  • What libraries you need to download?

 

Environment

  • Eclipse Indigo

Library

( 1 ) Create a new Java project

( 2 ) Create a new folder (lib) for the jar files

  • Copy all or the below jars from the downloaded Spring-Framework zip file
  • Add  them to the project build path

( 3 ) Create Java beans (Shape.java + Circle.java)

  • Create Shape interface (no need to create an interface, but just to use it for later example!)
  • Create Circle class implementing Shape
  • Place them as show below

Shape.java

package com.hmkcode.beans;

public interface Shape {
	void draw();
	void area();
}

Circle.java

package com.hmkcode.beans;

public class Circle implements Shape {

	double radius;

	public Circle(){
		System.out.println("Circle has been created!");
	}

	public Circle(double radius){
		this.radius = radius;
		System.out.println("Circle has been created radius = "+radius);
	}

	public double getRadius() {
		return radius;
	}
	public void setRadius(double radius) {
		this.radius = radius;
	}

	public void draw(){
		System.out.println("Drawing Circle");
	}
	public void area(){
		System.out.println("Area = "+Math.PI*Math.pow(radius, 2));
	}
}

( 4 ) Create Spring XML configuration file (spring-config.xml)

<?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="circle" class="com.hmkcode.beans.Circle"/>
</beans>

Place spring-config.xml as shown below

( 5 ) Create Test class (Main.java)

package com.hmkcode;

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

import com.hmkcode.beans.Circle;;

public class Main {

	public static void main(String args[]){

		// Laod spring-config.xml file
		ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/config/spring-config.xml");

		//get circle bean defined in spring-config.xml file
		Circle circle =(Circle)ctx.getBean("circle");

		//do something with the bean
                circle.setRadius(3.0);
                circle.draw();
                circle.area();
	}
}

Run the application you should get

Download Source Code: FirstTimeSpring.zip

Next:Spring XML Configuration