MichelReap
MichelReap

Reputation: 5770

Autowiring on HttpServlet

I want to inject a DAO dependency on my class that extends HttpServlet, is this even possible? I don't want to manually obtain the dependency from Application Context, but to have, if possible, real dependency injection on my Servlet instance. I tried annotating my Servlet with @Controller:

@Controller
public class ItemsController extends HttpServlet {

    @Autowired
    private IItemDAO itemDAO;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Item> items= itemDAO.getItems();
        req.setAttribute("items", items);
        gotoPage("/jsp/itemList.jsp", req, resp);
    }

    protected void gotoPage(String address, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

}

My application Context:

<context:annotation-config />
    <context:component-scan base-package="com.test.controller" />
    <bean id="itemsController" class="com.test.controller.ItemsController " />
    <bean id="itemDAO" class="com.test.dao.ItemDAO" />

Now to my understanding my Servlet (defined in web.xml) is not managed by Spring so my DAO dependency is not getting properly injected, how can I make Spring manage this bean?

Upvotes: 0

Views: 448

Answers (2)

Harald Wellmann
Harald Wellmann

Reputation: 12865

Another more lightweight solution is based on the HttpRequestHandler. See this blog for a detailed discussion.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

Now to my understanding my Servlet (defined in web.xml) is not managed by Spring so my DAO dependency is not getting properly injected

That's right. A Servlet is a component managed by a Servlet container. A @Controller bean is a component managed by Spring. They are two (usually) conflicting concepts. You should separate them.

Since @Controller is just an annotation, you can have a @Controller bean of type HttpServlet but it will not be managed or used by the Servlet container (or vice-versa).

If you want a Servlet which has injection targets, you can use the solutions provided here.

Upvotes: 2

Related Questions