I\'m new in Spring and want to connect spring ioc into my small(test) web-app.
I have such Servlet ProductServlet
:
public class Product
Here is a solution, which might help you:
public class ProductServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private RequestHelper requestHelper = null;
private requestHelperInit(HttpServletRequest request)
{
if(requestHelper == null)
{
ApplicationContext ap = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
requestHelper = ap.getBean(RequestHelper.class);
}
}
}
Then call requestHelperInit(request)
method in either your doGet()
or doPost()
method as the first statement.
If you are still looking for a solution, then I hope this will help you out.
You have a couple of choices. If you really want to inject a servlet, the problem is that the servlet container is already in charge of creating the servlet. Since injections are a creation time occurence, and it's a bit hard to get at this servlet creation, you have to use less elegant solutions. However, this question explains how to inject servlets.
On the other hand, you might consider aborting this approach. If you are really creating a web application, it's fairly uncommon to code directly to the servlet api. Why not choose one of the many web application frameworks that sit on top of the servlet api and provide higher level functionality, aka bells and whistles. One of the bells and whistles is that these frameworks provide convenient integration with Spring so you can easily inject your code. For instance, Struts 2 has a spring plugin that allows you to use spring to inject all of the objects created by the framework, including framework infrastructural components.
In your question you have
<bean name="ProductServlet" class="com.epam.productshop.controller.ProductServlet" scope="singleton">
<property name="requestHelper" ref="requestHelper"/>
</bean>
You cannot instantiate servlets with Spring container, they are instantiated by servlet container. You're merely declaring another instance of ProductServlet.
So, when the Servlet init()
method is called you should call
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, getServletContext());`
To inject the requestHelper declare an @Autowired
annotated field or property in your servlet:
private RequestHelper requestHelper;
@Autowired
public void setRequestHelper(RequestHelper requestHelper){
this.requestHelper = requestHelper;
}
from processInjectionBasedOnServletContext javadoc:
Process @Autowired injection for the given target object, based on the current root web application context as stored in the ServletContext.