Share on Google+Share on Google+

Spring Bean Example, Spring Bean Creation

In this tutorial you will see a very simple example of bean creation in spring framework.

Basic Bean Creation

The Spring bean can typically be POJO(Plain Old Java Object) in the IoC container. Here in this tutorial you will see at first a simple java bean file having two methods getMessage() and setMessage() and a default string value.

package net.roseindia;

public class BasicBean {
  private String mesg = "Spring is simple";

  public String getMessage() {
    return mesg;

  public void setMessage(String mesg) {
    this.mesg = mesg;

The context.xml connects every bean to every other bean that needs it.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  <bean id="basic" class="net.roseindia.BasicBean" />

The following class is a standard Java application with a main method. A BeanFactory will load bean definitions stored in a configuration source (such as an XML file)and it use the org.springframework.beans package to configure the beans. The ClassPathXmlApplicationContext takes the context defination files from the class path.

package net.roseindia;

import org.springframework.beans.factory.BeanFactory;

public class BasicBeanTest {
  public static void main(String[] args) {
  BeanFactory beanfactory = new ClassPathXmlApplicationContext("context.xml");
  BasicBean bean = (BasicBeanbeanfactory.getBean("basic");

When you run this application it will display output as shown below:

Spring is simple

Download this example code



Posted on: July 31, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null