Aks*_*nde 2 java spring spring-mvc spring-boot spring-java-config
每个函数的目的是什么。为什么spring给配置类赋予了两种不同的功能?我对两者感到困惑,我应该使用哪一个?
In a typical Spring application there are 2 ApplicationContext
instances, one is the so called root application context and the second (or third or ...) is the servlet application context.
The root application typically contains shared/general resources like DataSource
, services, repositories, etc... The servlet context contains beans specific for this context, generally things like view resolver, handler mappings, controllers etc. The servlet context uses the root context as a parent and thus can see the beans defined in there (the root doesn't know about the servlet contexts!).
In this typical setup the root context is loaded by the ContextLoaderListener
and the servlet context by the DispatcherServlet
.
在过去,人们会写一个 a web.xml
,其中包含一个servlet-listener
代表 the 的元素ContextLoaderListener
和一个servlet
代表 的元素DispatcherServlet
。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)
默认情况下将ContextLoaderListener
加载 aapplicationContext.xml
和DispatcherServlet
a <servlet-name>-servlet.xml
(因此 a dispatcher-servlet.xml
)。
从 Servlet 3.0 规范开始,可以web.xml
用基于 Java 的配置替换。Spring 花时间提供了已经完成基本配置的基类(例如 和 的注册ContextLoaderListener
)DispatcherServlet
。然而,由于它现在是完全基于 Java 的配置,因此ContextLoaderListener
需要DispatcherServlet
提供配置类列表,因为它没有可以检测到加载的默认类名。
因此,getRootConfigClasses()
将配置ContextLoaderListener
and 实际上是可选的(您可以返回null
or 一个空数组)。将getServletConfigClasses()
配置DispatcherServlet
(并且是必需的)。
归档时间: |
|
查看次数: |
1193 次 |
最近记录: |