Where do Spring bean configuration files go in a Maven WAR module?

后端 未结 2 705
离开以前
离开以前 2020-12-13 05:25

I\'ve looked at a bunch of sample projects and I can\'t seem to tease out a common best practice. I\'ve seen Spring bean config files sometimes go in the src/main/web

2条回答
  •  旧巷少年郎
    2020-12-13 05:41

    Application contexts in Spring can form hierarchies where child context has access to beans defined in parent context.

    A typical Spring MVC web application contains a hierarchy with two levels:

    • Root web application context loaded by ContextLoaderListener. Config location of this context is applicationContext.xml by default and can be configured using named contextConfigLocation, i.e. at the top level of web.xml. This context usually contains a core application logic.

    • Servlet-specifc context loaded by DispatcherServlet. Its config location is by default -servlet.xml and can be configured using named contextConfigLocation, i.e. at servlet level. This context usually contains a Spring MVC-related stuff (controllers, etc) since DispatcherServlet is a part of Spring MVC.

    The latter context is a child of the former.

    If web application doesn't use Spring MVC as a presentation framework, it doesn't have DispatcherServlet and its context. Some extremely simple Spring MVC samples doesn't have ContextLoaderListener and the root context (however, you need root context for cross-servlet functionality such as Spring Security).

    Config files of web application are by default located in webapp's root folder. However, they can be placed in the classpath (i.e. in src/main/webapp), in this case they are accessed via classpath: prefix. This may be useful if you are going to use some of these files in integration tests without servlet container. Also classpath: prefix may be useful when you want to load a config file from a separate artifact, i.e. from a jar file in /WEB-INF/lib.

提交回复
热议问题