Spring 单个上下文不继承根上下文



我有两个上下文xml驻留在WEB-INF文件夹中; applicationContext.xmlapp-servlet.xml .我在app-servlet中声明了这一点.xml

<context:component-scan base-package="com.training.hibernate.controller"/>

这在应用程序上下文中.xml

<context:component-scan base-package="com.training.hibernate.services"/>
<context:component-scan base-package="com.training.hibernate.dao"/>

我收到此错误

BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed;

如果我在app-servlet.xml中移动服务和dao的组件扫描,我没有收到任何错误。我假设app-servlet.xml没有继承applicationContext.xml

这是我的网络.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <display-name>Spring Web Application</display-name>
  <servlet>
      <servlet-name>app</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>app</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

这里有一些方向,我可以帮助你澄清不同的背景。在基于 Spring 的 Web 应用程序中通常有两个主要上下文:

  1. 应用程序上下文:包含 bean 的上下文,如服务、道等。

     <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>
            classpath:spring-config/applicationContext.xml
        </param-value>
    </context-param>
    <listener>
       <listener-class>
          org.springframework.web.context.ContextLoaderListener
       </listener-class>
    </listener>
    
  2. 然后是调度程序 servlet 的上下文。这包含特定于 Web 的 bean 。此上下文可以访问通过上面的 ContextLoaderListener 定义的 bean。

    <servlet> <servlet-name>app</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-config/app-servlet.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

请验证,您做对了。

最新更新