我可以在dispatcher-servlet中定义bean

时间:2013-06-25 08:56:49

标签: java spring java-ee spring-mvc

在我的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>

    

1 个答案:

答案 0 :(得分:3)

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

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

  

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

此处:Context hierarchies

  

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

在这里:17.2 The DispatcherServlet

  

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

不是最后一句:

  

您可以为给定的Servlet实例

定义新的特定于范围的bean