Declare bean in Spring container

With this example we are going to demonstrate how to declare a Bean in the Spring container. A Spring bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. In short, to declare a Class as a simple Spring Bean you should follow the steps below:

1. Include the following JARs in the classpath:

    – Spring framework libraries

  • org.springframework.asm-3.0.2.RELEASE.jar
  • org.springframework.beans-3.0.2.RELEASE.jarorg.springframework.context-3.0.2.RELEASE.jar
  • org.springframework.core-3.0.2.RELEASE.jar
  • org.springframework.expression-3.0.2.RELEASE.jar
  • – external libraries

  • commons.logging-1.1.1.jar

2. Create a simple Java class

The class has a simple method, printHello().

package com.javacodegeeks.snippets.enterprise;

public class HelloBean {

	public void printHello() {
		System.out.println("Hello World!");


3. Define the class as a Spring bean, in Spring configuration file.

The bean is defined in spring-beans.xml file inside the <bean> element. It has two attributes, the bean id and the class that is the class of the bean.

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

    <bean id="helloBean" class="com.javacodegeeks.snippets.enterprise.HelloBean" />


3. Run the application

In class we load the Spring configuration file, using the FileSystemXmlApplicationContext Class with the configuration file name. Using the getBean(String name) API method of ApplicationContext Class, we can get an instance of the helloBean and invoke its method.

package com.javacodegeeks.snippets.enterprise;

import org.springframework.context.ApplicationContext;

public class DeclareBeanInSpringContainer {

	public static void main(String[] args) throws Exception {

		ApplicationContext context = new FileSystemXmlApplicationContext("spring-beans.xml");

		HelloBean helloBean = (HelloBean) context.getBean("helloBean");



4. Output

The output is shown below:

Hello World!

This was an example of how to declare a Bean in the Spring container.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button