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 is simple enough to do this. First, 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.servlet;

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

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

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

            PrintWriter pw = res.getWriter();
            pw.print("User Details: " + user.toString());

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

Here are the supporting classes and the configurations.

package org.kodejava.servlet.dao;

import org.kodejava.servlet.model.User;

public interface UserDao {
    User getUser(Long userId);

package org.kodejava.servlet.dao.impl;

import org.kodejava.servlet.dao.UserDao;
import org.kodejava.servlet.model.User;

public class UserDaoImpl implements UserDao {
    public User getUser(Long userId) {
        if (userId == 1L) {
            return new User(1L, "jdoe", "John Doe");
        return new User();

package org.kodejava.servlet.model;

import java.util.Objects;

public class User {
    private Long id;
    private String username;
    private String realName;

    public User() {

    public User(Long id, String username, String realName) { = id;
        this.username = username;
        this.realName = realName;

    // Getters and Setters


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

    <bean id="userDao" class="org.kodejava.servlet.dao.impl.UserDaoImpl"/>



<web-app xmlns=""


Maven dependencies

<!-- -->
<!-- -->

Maven Central Maven Central