Spring Tutorial

Spring Tutorial explains step by step details of setting / configuring Spring with Eclipse

The Spring Framework is a free and open source framework using for the development of java enterprise applications

Spring framework consists of several different modules including Aspect Oriented Programming, Inversion Control, Model View Controller, Data Access, Transaction Management, Batch Processing, Remote Access & Spring JDBC Template will really ease the development effort of coding team.

In this example you will learn how to set / injects a bean property via setter injection using spring framework.

Note

You can also check following related spring tutorials

  1. Spring JDBC Template Tutorial
  2. Spring MVC 4 Example
  3. Spring MVC 4 REST Example
Required Libraries

You need to download

  1. JDK 6
  2. Eclipse 3.7
  3. Spring

Following jar must be in classpath

  1. org.springframework.asm-3.0.6.RELEASE.jar
  2. org.springframework.beans-3.0.6.RELEASE.jar
  3. org.springframework.context-3.0.6.RELEASE.jar
  4. org.springframework.context.support-3.0.6.RELEASE.jar
  5. org.springframework.core-3.0.6.RELEASE.jar
  6. org.springframework.expression-3.0.6.RELEASE.jar
  7. antlr-2.7.7.jar
  8. commons-logging-1.1.1.jar

Create domain model

Create domain model named student. Here we are going to inject 2 properties via setter injection.

Consider the following Student bean class

package com.javatips;

public class Student {

 
private String name;
 
private int age;

 
public String getName() {
   
return name;
 
}

 
public void setName(String name) {
   
this.name = name;
 
}

 
public int getAge() {
   
return age;
 
}

 
public void setAge(int age) {
   
this.age = age;
 
}

 
public String toString() {
   
return "Student " + name + " is " + age + " years old";
 
}
}

beans.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.xsd">

    <bean id="student" class="com.javatips.Student">
        <property name="name" value="Rockey" />
        <property name="age" value="29" />
    </bean>

</beans>

Test Program

package com.javatips;

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

public class Main {

 
public static void main(String[] args) {
   
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Student student =
(Student)context.getBean("student");
    System.out.println
(student);
 
}
}
Output
Student Rockey is 29 years old








Your email address will not be published. Required fields are marked *