Creating the Project

  • Open Eclipse (Kepler)
  • New -> Maven Project
  • Simple Project
  • Group Id: com.skills421.examples.spring
  • Artifact Id: Spring2.5.6Example
  • Finish

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.skills421.examples.spring</groupId>
  <artifactId>Spring2.5.6Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
		</dependency>
	</dependencies>
</project>

Person bean

src/main/java
com.skills421.examples.spring.model.Person

package com.skills421.examples.spring.model;

public class Person
{
	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()
	{
		StringBuilder sb = new StringBuilder();
		
		sb.append("Person[");
		sb.append("name=");
		sb.append(this.getName());
		sb.append(", age=");
		sb.append(this.getAge());
		sb.append("]");
		
		return sb.toString();
		
	}
}

ApplicationContext

src/main/resources
ApplicationContext.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="johnDoe" class="com.skills421.examples.spring.model.Person">
		<property name="name" value="Jon Doe" />
		<property name="age" value="21" />
	</bean>
</beans>

Main

src/main/java
com.skills421.examples.spring.Main

package com.skills421.examples.spring;

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

import com.skills421.examples.spring.model.Person;

public class Main
{

	public static void main(String[] args)
	{
		ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
 
		Person p1 = (Person) context.getBean("johnDoe");
		System.out.println(p1.toString());
	}
}

Output

Person[name=Jon Doe, age=21]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s