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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

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

</beans>

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;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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");
        hello.sayHello();
    }
}

Spring Hello Bean Example