Java : Spring basics

Download Spring 3.0 RELEASE and copy dist/* and commons-logging.jar to Eclipse project class-path.

There are two ways to Instantiate Spring IoC container
– ClassPathXmlApplicationContext
– FileSystemXmlApplicationContext

Let’s use ClassPathXmlApplicationContext, the config xml will be loaded from the class path.

HelloSpring3.java

package sam.spring;

public class HelloSpring3 {
	public void sayHello() {
		System.out.println("Hello Spring 3");
	}
}

Driver.java

package sam.spring;

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

public class Driver {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"HelloSpring3.xml");
		HelloSpring3 hs3 = (HelloSpring3) context.getBean("helloBean");
		hs3.sayHello();
	}

}

HelloSpring3.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" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="helloBean" class="sam.spring.HelloSpring3" />

</beans>

Output

Mar 06, 2012 4:43:08 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@8ff4cf: startup date [Tue Mar 06 16:43:08 IST 2012]; root of context hierarchy
Mar 06, 2012 4:43:08 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [HelloSpring3.xml]
Mar 06, 2012 4:43:09 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@63a8af: defining beans [helloBean]; root of factory hierarchy
Hello Spring 3
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

%d bloggers like this: