This example will show how to configure and load simple spring bean.
Sample java Bean that is being loaded from another class
package com.codesimplify;

public class Administrator {
	private String firstName;
	private String lastName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	public void setLastName(String lastName) {
		this.lastName = lastName;
	public String toString(){
		return "FirstName: "+firstName +" , LastName: "+lastName;

Create Instance of class without Spring Framework

Following example will show us how App class will create instance of Administrator class
package com.codesimplify;

public class App {

	public static void main(String[] args) {
		Administrator administrator=new Administrator();

Example to configure as Spring Bean and load it in App class.

This flow requires 3 steps.

  • Define Java Bean in Spring Configuration file
  • Load java beans defined in configuration file
  • retrieve/access the loaded bean using bean identifier

Define Java Bean in Spring Configuration file

Define Administrator class as spring bean in spring configuration file as under. We can give any name to configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

  <bean name="adminBean" class="com.codesimplify.Administrator">
       <property name="firstName" value="john" />
       <property name="lastName" value="smith" />

Load java beans defined in configuration file And retrieve loaded bean
package com.codesimplify.spring.core;

import org.springframework.context.ApplicationContext;

import com.codesimplify.Administrator;

public class App {

	public static void main(String[] args) {
		// Load Beans into Spring Application Context
		ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
		// Retrieve loaded Bean from application context
		Administrator admin=(Administrator)context.getBean("adminBean");



16:41:26.684 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'adminBean'
FirstName: john , LastName: smith
  • If we observe the output above, first line indicates that the returned instance is a cached and singleton. After loading context, whenever we call , it returns same instance of Administrator bean
  • Spring configuration allows to set firstname and lastName of the Administrator without modifying the code.
  • Spring configuration allows to provide sub class of the Administrator without changing the code
Simple Spring Bean Example

One thought on “Simple Spring Bean Example

Leave a Reply

Your email address will not be published. Required fields are marked *