Spring root application context and servlet context confusion

后端 未结 2 1006
一个人的身影
一个人的身影 2020-12-23 22:50

I know that I need to register classes annotated @Controller in my servlet context to make my webapp accesible. Usualy, I do it the following way:



        
2条回答
  •  庸人自扰
    2020-12-23 23:30

    Most Spring MVC applications have one root context containing all service layer / DAO layer beans, and one servlet context per spring dispatcher servlet of the application, which contains (at least) the controllers of each servlet.

    The idea being that is that one application might have several servlet dispatchers, for example one for URL /shopping/* and the other for URL /reporting/*, each with it's own set of controllers.

    The controllers of one servlet dispatcher are isolated from each other, meaning although they are also Spring beans, they cannot be injected in each other.

    Service layer and DAO beans in the root context are visible in all servlet contexts, so Service layer beans can be injected in any controller, but not the other way around.

    The root context is said to be the parent of the controller servlet context/contexts.

    It's all meant to be a mechanism of isolating groups of beans from each other to ensure no unmeant dependencies are possible.

    Given this and going through the questions:

    • If I'm trying to create TimeServiceWs bean inside root application context, as expected it doesn't see SimpMessagingTemplate bean and throws NoSuchBeanDefinitionException: Move the SimpleMessagingTemplate to the root context, it's a bean like a DAO that can be useful anywhere in the application so it should be in the shared root context.

    • If I'm trying to create TimeServiceWs bean inside servlet context, then I'm unable to autowire it to any another service: If it's meant to be autowired to other services, leave it in the root context then.

      - If I move all my configurations to servlet context, all beans are successfully created, but I get java.lang.IllegalStateException: No WebApplicationContext found: Do the opposite, move basically all beans to the root context, and leave on the servlet context only the beans that are specific of that part of the application, many times only the controllers.

提交回复
热议问题