Make ServletContextListener spring aware

前端 未结 4 2047
鱼传尺愫
鱼传尺愫 2021-02-12 11:14

I am plugging in Spring to existing Java EE web Application. I have following lines in my web.xml:


    com.MyContextListen         


        
4条回答
  •  醉话见心
    2021-02-12 11:43

    Well,

    We had a similar scenario of configuring an exiting Jersey web services app to use Spring for dependency injection. Our Jersey webapp had extended ContextLoaderListener as follow

    public class XServletContextListener extends ContextLoaderListener {
        ... 
        @Override
        public void contextInitialized(ServletContextEvent arg0) {
            super.contextInitialized(arg0);
            ....
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent arg0) {
            super.contextDestroyed(arg0);
            ....
        }
    } 
    

    where ContextLoaderListener is

    import org.springframework.web.context.ContextLoaderListener;
    

    We included the jersey-spring bridge with all spring dependencies including applicationContext.xml as follow

    
    
        
        ....
        ....
    
    

    And obviously needed to make sure that XServletContextListener is included in the web.xml as follow

    
        contextConfigLocation
        /WEB-INF/applicationContext.xml
    
    
        com.xxx.**.XServletContextListener
    
    

    Followed by servlet and its init-param values and servlet mapping. You can obviously adopt annotation config in place of xml confib in which case you would need to use WebListener annotation.

    We use a variety of annotations such as

    @Component for objects
    @Service for services 
    @Repository for DAOs
    @Controller for controllers/resources 
    @ContextConfiguration for tests
    

    Everything is loaded and autowired by Spring framework.

提交回复
热议问题