getRootConfigClasses和getServletConfigClasses区别

来源:互联网 发布:js中offsetwidth 编辑:程序博客网 时间:2024/06/05 11:36

在spring in action这本书中关于配置DispatchServlet中如果用非xml的配置方式有这么一段代码(当时很疑惑着两个配置类有什么区别):

package spittr.config;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class SprittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{    //将DispatcherServlet映射到"/"    @Override    protected String[] getServletMappings(){    return new String[]{"/"};    }     //指定根配置类    @Override    protected Class<?>[] getRootConfigClasses(){        return new Class<?>[]{RootConfig.class};    }    //指定配置类    @Override    protected Class<?>[] getServletConfigClasses(){        return new Class<?>[] {Webconfig.calss};    }

后续需要分别写RootConfig.class和WebConfig.class,这里就不把代码列出来了。
WebConfig配置类中主要是内容是启用组件扫描,配置视图解析器,配置静态资源的处理。
RootConfig配置类加载的是驱动应用后端的中间层和数据层组件,是父上下文。


在StackOverFlow上有这么一个解释我觉的说的很清楚.
原文链接

Spring’s ApplicationContext provides the capability of loading multiple (hierarchical) contexts, allowing each to be focused on one particular layer, such as the web layer of an application or middle-tier services.

One of the canonical examples of using hierarchical ApplicationContext is when we have multiple DispatcherServlets in a web application and we’re gonna share some of the common beans such as datasources between them. This way, we can define a root ApplicationContext that contain all the common beans and multiple WebApplicationContexts that inherit the common beans from the root context.

In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to a given Servlet instance.

Typical context hierarchy in Spring Web MVC (Spring Documentation)


If you’re living in a single DispatherServlet world, it is also possible to have just one root context for this scenario:

Single root context in Spring Web MVC (Spring Documentation)


翻译过来的意思如下:
spring的ApplicationContext提供加载多层上下文的能力,允许每个上下文只关注特定层,例如一个应用的web层或者中间层服务.其中一个经典的是使用分层ApplicationContext的例子就是,当我们有多个DispatchServlet在一个应用和我们想要共享其中的普通bean例如datasource。这时候我们可以定义一个根上下文即
root ApplicationContext,这个根上下文包含了普通的bean和从根上下文继承了普通bean的多个WebApplicationContext。
在web mvc框架中,每个DispatchServlet都有自己独自的WebApplicationContext,这个WebApplicationContexti继承了所有已经在 root WebApplicationContext定义了的bean。这些被继承的bean可以被特定的复写,而且对于一个给定的servlet实例你能够在本地定义新的指定范围的bean.

就酱。

1 0
原创粉丝点击