Accessing a Spring bean from a servlet

I’m using Ajaxtags to implement an ajax-enabled form with dynamic dropdown fields. In order to access my DAO object (which is a Spring managed bean)  to get the dropdown options, I had to have access to the Application context from a regular Servlet.

The solution is very simple, but since I had some troubles finding it, I’m adding it here for future reference, and for anyone who’s looking for the same. Basically, you use the WebApplicationContextUtils object from the spring framework to get a reference to your bean. Inside the doGet() method I have:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object myDao = context.getBean("daoBeanName");

It’s that easy… really.

20 thoughts on “Accessing a Spring bean from a servlet

  1. You do not have to use a servlet, you can use you framework action to return the result. We included the servlet as an example but in the release there is an abstract struts action an the same can be done with Spring.

  2. Accediendo a un bean Spring desde un servlet.
    Una buena solucion dificil de encontrar en la web.
    Great!!, thank you

  3. This is exactly what’s missing in Spring Tutorial, "Developing a Spring Framework MVC application step-by-ste".

    Cool stuff.

    Jiryih Tsaur

  4. Is there a way to make my servlet a bean? I can’t use MVC because in my servlet I need to send data back piece by piece. Thx

  5. If I’m not mistaken new instance will be created when you say context.getBean(“daoBeanName”);

    This means, this is stateless (prototype). Please correct me is I’m wrong. If this is true how do we create a singleton instance?

  6. It will not work in the init-method, as the WebApplicationContext will always be null there.

Leave a Reply