Share on Google+Share on Google+

Spring Bean Example, Spring Bean Creation

Advertisement
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.

BasicBean.java

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.

Context.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="basic" class="net.roseindia.BasicBean" />
</beans>

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. 

BasicBeanTest.java

package net.roseindia;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

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

Spring is simple

Download this example code

Advertisements

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.