How do I declare a bean in Spring application?

In this example we will learn how to declare a bean in Spring Application. We are going to build a simple Maven project to demonstrate it. So let’s begin by setting up our Maven project.

Creating a Maven Project

Below is the directory structure of our Maven Project.

├─ pom.xml
└─ src
   └─ main
      ├─ java
      │  └─ org
      │     └─ kodejava
      │        └─ spring
      │           └─ core
      │              ├─
      │              ├─
      │              └─
      └─ resources
         └─ spring.xml

Configuring Maven pom.xml File

We need to create a pom.xml file and add our project configuration and library dependency.

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




Creating a Bean

Next we will create a simple bean called HelloImpl. This bean implements an interface called Hello with a single method sayHello() to be implemented. Here is the interface it’s implementation definition.

package org.kodejava.spring.core;

public interface Hello {
    void sayHello();
package org.kodejava.spring.core;

public class HelloImpl implements Hello {

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

Register the Bean in Spring Configuration

After having the bean we need to create the Spring configuration, which is an xml file, and we named it spring.xml. The bean declared using the bean element in the configuration file. At minimum the declaration contains the bean’s id and it’s class.

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

    <bean id="hello" class="org.kodejava.spring.core.HelloImpl" />


Use the Bean in Our Application

Now we have the bean declared in the Spring container. The next step show you how to get the bean from the container and use it in our program. There are many ways that can be used to load the Spring container. Here we will use the ClassPathXmlApplicationContext. This class load the configuration that found in the runtime classpath.

package org.kodejava.spring.core;


public class HelloWorldDemo {
    public static void main(String[] args) {
        String config = "spring.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);

        Hello hello = (Hello) context.getBean("hello");

Leave a Reply

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