Announcement Announcement Module
No announcement yet.
Get Spring Annotated bean in Servlet's init method Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Get Spring Annotated bean in Servlet's init method

    Hello everyone,

    I am using Spring 3.0 IOC & MVC with my application. And I came across a requirement that I want a spring bean to be accessed in my Servlet.

    So, I made an entry in web.xml (for servlet), and in servlet's init() method I wrote a snippet to get Spring bean. To get Spring bean I'd used bellow snippet:

    ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    userService = applicationContext.getBean("userService", IUserService.class);
    But by doing this, I am getting applicationContext value as null.

    Servlet is configured as load-on-startup with order 2.

    Spring beans are registered as annotated classes. (Controller, Model, Repository)

    Can any one help me out?

  • #2
    How do you load the spring beans? With the ContextLoaderListener as that is what you can get access to NOT the beans loaded by the DispatcherServlet.


    • #3
      Thanks for the reply Marten.

      Loaded Spring beans using DispatcherServlet. And that dispatcherservlet-servlet.xml file contains information about bean files. So, do I need to add ContextLoaderListener to get Spring Bean in Servlet class?

      Also one thing I came to know that,
      it is recommended that you put you repositories, services, and shared beans within ContextLoaderListener area, while controllers should be mentioned in *-servlet.xml file
      mentioned on this post. But in my case I'd used annotation for all Controllers, Services and Repositories, by providing

      <context:annotation-config />
      <context:component-scan base-package />
      So do you thing it will conflict somewhere?

      I am new to this, so having doubt that this will conflict somewhere because the same kind of description will be there in ContextLoaderListener file.

      Please guide me for the same.
      Last edited by parth.bhagat; May 18th, 2012, 04:36 AM.


      • #4
        Use the search as the question regarding how to split the files and use component-scanning for both the ContextLoaderListener and DispatcherServlet. In short your current setup will duplicate your bean instances leading to all sorts of problems, as stated the CLL should load only Services and Repositories the DS only web related stuff.