Spring injection Into Servlet

后端 未结 4 1814
Happy的楠姐
Happy的楠姐 2020-11-29 21:17

So I have seen this question:

Spring dependency injection to other instance

and was wondering if my method will work out.

1) Declare beans in my Spri

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 21:57

    I wanted to leverage on the solution provided by Sotirios Delimanolis but adding transparent autowiring to the mix. The idea is to turn plain servlets into autowire-aware objects.

    So I created a parent abstract servlet class that retrieves the Spring context, gets and autowiring-capable factory and uses that factory to autowire the servlet instances (the subclasess, actually). I also store the factory as an instance variable in case the subclasses need it.

    So the parent abstract servlet looks like this:

    public abstract class AbstractServlet extends HttpServlet {
    
        protected AutowireCapableBeanFactory ctx;
    
        @Override
        public void init() throws ServletException {
            super.init();
            ctx = ((ApplicationContext) getServletContext().getAttribute(
                    "applicationContext")).getAutowireCapableBeanFactory();
            //The following line does the magic
            ctx.autowireBean(this);
        }
    }
    

    And a sevlet subclass looks like this:

    public class EchoServlet extends AbstractServlet {
    
        @Autowired
        private MyService service;
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
            response.getWriter().println("Hello! "+ service.getMyParam());
        }
    }
    

    Notice the only thing EchoServlet needs to do is to declare a bean just in common Spring practice. The magic is done in the init() method of the superclass.

    I haven't tested it thoroughly. But it worked with a simple bean MyService that also gets a property autowired from a Spring-managed properties file.

    Enjoy!


    Note:

    It's best to load the application context with Spring's own context listener like this:

    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    
    

    Then retrieve it like this:

    WebApplicationContext context = WebApplicationContextUtils
        .getWebApplicationContext(getServletContext());
    ctx = context.getAutowireCapableBeanFactory();
    ctx.autowireBean(this);
    

    Only spring-web library needs to be imported, not spring-mvc.

提交回复
热议问题