How do I declare a bean in Spring application?

This example will show you how to declare a bean in the Spring container. First we will create a simple bean called HelloImpl with a method called sayHello(). That’s all we need for our bean.

package org.kodejava.example.spring.hello;

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

public class HelloImpl implements Hello {

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

After having the bean we need to create the Spring configuration, which is an xml file. 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=""

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


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 use 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.example.spring.hello;

import org.springframework.context.ApplicationContext;

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

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

Spring Hello Bean Example