All Spring Framework beans get duplicated, becase of doubled context (servlet+ContextLoaderListener)

前端 未结 1 952
长情又很酷
长情又很酷 2021-02-11 00:16
  • If I create spring context by dispatcher servlet, I got an error inDelegatingFilterProxy filter:

    java.lang.IllegalStateExc         
    
    
            
1条回答
  •  青春惊慌失措
    2021-02-11 00:40

    if you use spring related servlet filters and also use mvc controllers, then you need both:

    • ContextLoaderListener AND
    • DispatcherServlet-spring-configuration

    (See ContextLoaderListener or not?)

    Both create their own servlet context. The ContextLoaderListener create the parent-context (sometimes called the inner-context). And the DispatcherServlet create a child-context (of the parent context) (sometimes called the outer-context). The beans of the child-context can access the beans of the parent-context, but not the other way around.

    In a not too simple web application you need both contexts, because the there are many servlet filters that requires an already created spring context. On the other hand, all the controller stuff needs a ServletContext, and this is only created by the Dispatcher Servlet.

    Another point is, that you should not have every bean created twice (sometimes this is no problem, other times it is). So you need to have two spring configurations, one for the inner context, one for the other context. And you need to decide for every bean whether it belongs to the inner or to the outer context.

    The rule of thumb is: put every thing in the inner context, except that stuff that requires a Servlet context or is heavily tied to the Web-frontend, like MVC-Controllers, Tiles configuration, ....

    0 讨论(0)
提交回复
热议问题