'How to inject dependency into Servlet?

I've created a Servlet and added configuration in web.xml:

<servlet>
     <servlet-name>MyServlet</servlet-name>
     <servlet-class>com.foo.web.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/myservlet/*</url-pattern>
</servlet-mapping>

Registered a bean for it:

<bean id="MyServlet" class="com.foo.MyServlet" autowire="byType">
    <property name="MyService" ref="MyManager"/>
</bean>

I've created a bean which is injected into MyServlet

<bean id="MyManager" class="com.foo.MyService" autowire="byType">
</bean>

There s a setter method in the servlet used by spring for setting the property to the bean:

 public class MyServlet extends HttpServlet {

       private static final long serialVersionUID = 1L;

       private MyManager myService;
    
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse response) throws 
          ServletException, IOException {
        
      }
    
       public void setMyService(MyManager myManager){
          this.myService = myManager;
       }
    
}

Autowiring is done correctly during the application startup, but when Servlet "catches" some request, this property (myService) is not instantiated (it's null). How or can I even have a Servlet with some autwired properties?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source