【问题标题】:Can I define beans inside dispatcher-servlet我可以在 dispatcher-servlet 中定义 bean
【发布时间】:2013-06-25 08:56:48
【问题描述】:

在我的 web.xml 中,我删除了 contextConfigLocation,而不是指向 application context,我在调度程序 servlet 中定义了我的 bean。这是允许的还是 Spring 肯定会寻找 contextConfigLocation?

<!--context-param>        //This part is commented. Is this allowed?
    <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-->

通过调度程序 servlet 中的 bean...

<bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource"
        p:driverClassName="oracle.jdbc.driver.OracleDriver"
        p:url="jdbc:oracle:thin:@localhost:1521:Xe"
        p:username="hibernate"
        p:password="hibernate"></bean>


【问题讨论】:

  • 简短回答 - 可以。

标签: java spring jakarta-ee spring-mvc


【解决方案1】:

是的,但它们仅在网络环境中可见。看这个答案Spring can't see beans between servlet-context and contextConfigLocation beans

引用 WebApplicationContext 的 Spring Framework API(在编写 3.2.2 时):

与通用应用程序上下文一样,Web 应用程序上下文是 层次分明。 每个应用程序都有一个根上下文,而 应用程序中的每个 servlet(包括 MVC 框架)有自己的子上下文

也在这里:Context hierarchies:

例如,如果您正在开发 Spring MVC Web 应用程序,您 通常会有一个通过 Spring 加载的 root WebApplicationContext ContextLoaderListener 和一个 child WebApplicationContext 通过 Spring 的 DispatcherServlet。这导致了父子上下文 共享组件和基础架构配置所在的层次结构 在根上下文中声明并在子上下文中使用 特定于网络的组件。

在这里:17.2 The DispatcherServlet:

Spring 中的ApplicationContext 实例可以是作用域的。在 Web MVC 中 框架,每个 DispatcherServlet 都有自己的 WebApplicationContext, 它继承了根中已经定义的所有bean WebApplicationContext。这些继承的 bean 可以在 特定于 servlet 的范围,您可以定义新的特定于范围的 bean 本地给定的 Servlet 实例。

不是最后一句话:

您可以在给定的 Servlet 实例本地定义新的特定于范围的 bean

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多