Skip to content

Autowire Java Servlet

kimi edited this page Nov 18, 2015 · 1 revision
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class AutowireServlet extends HttpServlet {

    @Autowired
    HelloService helloService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        autowireServlet(this, config.getServletContext(),
                             AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
    }

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        resp.getWriter().write(helloService.sayHello("autowire"));
    }

    void autowireServlet(HttpServlet servlet,
                         ServletContext context,
                         int autowireMode) {
        WebApplicationContextUtils.getWebApplicationContext(context)
            .getAutowireCapableBeanFactory()
            .autowireBeanProperties(servlet, autowireMode, false);
    }
}
Clone this wiki locally