How do I inject a bean through constructors?

The following example demonstrate how we can inject a bean through their constructors. We will create a couple interfaces and classes for this purpose. First we will create the Singer interface and the Instrument interface. The Singer interface define a single method call sing() that will enable the implementation to sing a song.

The second interface, Instrument also define a single method call play(). This method will allow the implementation to play some instrument. After defining our example interface we create an implementation for each of them. The class will be called the AnySinger and Piano.

Here are the code that we have to code so far:

package org.kodejava.example.spring;

public interface Singer {
    /**
     * Sing a song.
     */
    void sing();
}
package org.kodejava.example.spring;

public interface Instrument {
    /**
     * Play an instrument.
     */
    void play();
}
package org.kodejava.example.spring;

public class AnySinger implements Singer {
    private String song = "Nana nana nana";
    private Instrument instrument = null;

    public AnySinger() {
    }

    /**
     * A constructor to create singer to sing a specific song.
     *
     * @param song the song title to sing.
     */
    public AnySinger(String song) {
        this.song = song;
    }

    /**
     * A constructor to create singer to sing a song while playing
     * an instrument.
     *
     * @param song the song title to sing.
     * @param instrument the instrument to play.
     */
    public AnySinger(String song, Instrument instrument) {
        this.song = song;
        this.instrument = instrument;
    }

    @Override
    public void sing() {
        System.out.println("Singing " + song);
        if (instrument != null) {
            instrument.play();
        }
    }
}
package org.kodejava.example.spring;

public class Piano implements Instrument {

    @Override
    public void play() {
        System.out.println("Playing the Piano");
    }
}

We have created the classes that we need for our program to work. The next step is to create our spring configuration file. This will configure our bean in the spring container and wire all the dependency required by the bean.

<?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="piano" class="org.kodejava.example.spring.Piano"/>

    <bean id="singer" class="org.kodejava.example.spring.AnySinger">
        <constructor-arg value="Dust in The Wind"/>
        <constructor-arg ref="piano"/>
    </bean>

</beans>

In the spring configuration we declare two beans. The first bean is the piano bean, which is a type of instrument. The main object of our example is the singer bean. To create the singer we use a constructor injector to inject some values or object reference for the bean to use.

In the singer bean we use the <constructor-arg/> element to inject dependency for the object. The value attribute can be use for passing a string or other primitive value. To pass an object reference we need to use the ref attribute.

Finally, we’ll create a simple program to run our constructed spring application. The code will include the process of loading our spring container, obtaining the bean from the container. Let’s see our singer in action.

package org.kodejava.example.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SingerDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("Singer.xml");

        Singer singer = (Singer) context.getBean("singer");
        singer.sing();
    }
}

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

How do I get a spring’s bean from a servlet?

I have created a servlet based web application and I want to used Spring beans in it. So how do I do this in my servlet. Well, it simple enough to do this. First of all I have to obtain the Spring’s WebApplicationContext, from where I can grab the required bean by my servlet.

Let’s see some lines of code on how to do it, here we go:

package org.kodejava.example.servlet;

import org.kodejava.example.servlet.dao.UserDao;
import org.kodejava.example.servlet.model.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SpringBeanServletExample extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        ServletContext context = getServletContext();
        WebApplicationContext ctx =
                WebApplicationContextUtils
                        .getWebApplicationContext(context);
        UserDao dao = ctx.getBean("userDao", UserDao.class);

        Long userId = Long.valueOf(req.getParameter("user_id"));
        User user = dao.getUser(userId);

        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        pw.print("User Details: " + user.toString());
        pw.flush();
    }
}

Inside the Java Servlet doGet() method above I get the ServletContext, next the WebApplicationContextUtils help me to get Spring’s WebApplicationContext. With this object in my hand I can get my UserDao implementation and do a query from database.

Spring Bean Servlet Example

Spring Bean Servlet Example