为什么spring-servlet.xml中的Beans无法访问我applicationContext.xml中的Beans?

4
我在这里有一个问题,就是如何让在“applicationContext.xml”中定义的Bean在“spring-servlet.xml”中定义的控制器中可用,这样我就可以避免这种错误。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '/home' defined in ServletContext resource [/WEB-INF/mmapp-servlet.xml]: Cannot resolve reference to bean 'equipementService' while setting bean property 'equipementService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'equipementService' is defined

applicationContext.xml

<?xml version="1.0" ?>
<!DOCTYPE beans PUBLIC 
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <bean name="equipementService"
        class="mmapp.service.SimpleEquipementService" />
    <bean name="equipement1"
        class="mmapp.domain.Equipement" />

</beans>

mmapp-servlet.xml

<?xml version="1.0" ?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean name="/home" class="mmapp.web.HelloController">
        <property name="equipementService" ref="equipementService" />
    </bean>
</beans>
2个回答

7

一个基于Spring的Web应用程序通常有多个运行时Spring应用程序上下文 -

  1. 根应用程序上下文(在servlet容器启动期间加载),这里通常放置服务Bean - 根应用程序上下文通过使用ContextLoaderListener加载,通常在web.xml文件中使用以下条目:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>

以下是翻译的结果:
  1. 一个或多个Web应用程序上下文,被视为根应用程序上下文的子级,包含与UI相关的bean - 控制器等。这是通过使用Spring提供的特殊Servlet - Dispatcher Servlet进行配置的,该Servlet知道如何适当地将调用委派给Spring容器。根应用程序上下文中的bean对此处定义的bean可见,但反之不成立 - 这样提供了UI层和服务层之间的分离级别。这是web.xml文件中的典型配置条目:
<servlet>
    <servlet-name>lovemytasks</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/mmapp-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

如果您以这种方式定义了bean,那么equipementService应该对您的控制器可见。

我的web.xml文件只有ContextLoaderListener监听器标签,现在加上<context-param>标签后一切都好了,谢谢!!另外一个奇怪的问题是,在上下文文件中,bean必须在其他bean使用之前声明... - elaich
是的,您必须声明bean - 但是这可以使用Spring中的注释支持非常容易地完成,以至于您甚至可能不需要显式配置,除了稍微引导一下 - 这是一个参考:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-annotation-config - Biju Kunjummen

1
我不是专家,也不确定这是否可能是一个问题,但我有一个建议。 您能否发布您的Web应用程序描述符(web.xml)?它是否包含context-param?
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
</context-param>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接