Spring hello world example

 Posted On  | Yashwant Chavan 

Quick Guide to write spring hello world program. Learn How to configure spring bean configuration.

Refer below example to display hello world using spring.The Spring 3.0 required JDK version 5 or Above. In our case we are using Java6.

Configure the bean details in SpringHelloWorld.xml file. Which is used to declared bean configuration <bean> tag having several properties. Here we are use only id="helloWorldBean" and class="com.technicalkeeda.src.SpringHelloWorld" properties.id property indicates bean identifier, it should be the unique name. class is normally the actual implementation class of the bean being described in the bean definition.

Refer Spring's bean configuration file.

<?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="helloWorldBean" class="com.technicalkeeda.src.SpringHelloWorld" />
</beans>

SpringHelloWorld.java class is simple pojo(Plain Old Java Object). Its a simple bean

package com.technicalkeeda.src;

public class SpringHelloWorld {
 
 public void hello(){
  System.out.println("Hello World..");
 }

}

SpringHelloWorldTest.java class is used to call getBean method of Bean Object Factory using bean id. Which is configured in the "SpringHelloWorld.xml" file.

package com.technicalkeeda.src;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class SpringHelloWorldTest {

 public static void main(String[] args) {

  XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
    "SpringHelloWorld.xml"));

  SpringHelloWorld springHelloWorldObject = (SpringHelloWorld) beanFactory
    .getBean("helloWorldBean");
  springHelloWorldObject.hello();
 }
}

The BeanFactory is the actually a container which instantiates, configures, and manages a number of beans. ClassPathResource class is used to load resources which should be obtained from the classpath. Created a factory using Spring's XmlBeanFactory class, which reads an XML file that declaratively defines the classes.

Spring Hello World Output

INFO: Loading XML bean definitions from class path resource [SpringHelloWorld.xml]
Hello World..


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0421 seconds.