dde*_*ele 118
从春季文档
Spring可以轻松集成到任何基于Java的Web框架中.您需要做的就是在web.xml中声明ContextLoaderListener并使用contextConfigLocation 来设置要加载的上下文文件.
的<context-param>:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用WebApplicationContext来获取bean的句柄.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
Run Code Online (Sandbox Code Playgroud)
fmu*_*car 34
您还可以相对于当前类路径指定上下文位置,这可能是更可取的
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
Ani*_*kur 17
您还可以在定义servlet本身时加载上下文(WebApplicationContext)
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>admin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)
而不是(ApplicationContext)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
或者可以一起做.
仅使用WebApplicationContext的缺点是它将仅为此特定Spring入口点(DispatcherServlet)加载上下文,其中上述方法将为多个入口点加载上下文(例如,Webservice Servlet, REST servlet等等)
加载的ContextLoaderListener上下文实际上将是专门为DisplacherServlet加载的上下文.因此,基本上您可以在应用程序上下文中加载所有业务服务,数据访问或存储库bean,并将控制器分离出来,将解析程序bean查看到WebApplicationContext.
| 归档时间: |
|
| 查看次数: |
161425 次 |
| 最近记录: |