2012-03-07 32 views
1

我得到了這個異常。這是我的代碼:沒有定義名爲「userDao」的bean

ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/servlet-context.xml"); 
UserDao userDao = (UserDao) context.getBean("userDao"); 

這是位於/myproject/WebContent/WEB-INF/spring/appServlet/servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 

    <beans:bean id="userDao" class="it.ex.home.dao.JdbcUserDao"> 
     <beans:property name="dataSource" ref="dataSource"/> 
    </beans:bean> 

    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
     <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
     <beans:property name="url" value="jdbc:mysql://localhost:3306/hibernate_db"/> 
     <beans:property name="username" value="root"/> 
     <beans:property name="password" value="root"/> 
    </beans:bean> 

    <context:component-scan base-package="it.ex.home" /> 

</beans:beans> 

怎麼我的servlet-context.xml文件我能解決這個問題嗎?

+0

奇怪的,你可以試試'的​​getBean(JdbcUserDao.class)'?另外,你確定你正在加載正確的文件嗎?使語法不正確的XML,看看是否抱怨。 – 2012-03-07 16:50:37

回答

1

classpath*:/servlet-context.xml將從您的應用程序的類路徑的的每個servlet-context.xml資源加載。

/myproject/WebContent/WEB-INF/spring/appServlet/servlet-context.xml但是,根本不在類路徑根上,所以Spring會忽略你的文件並建立一個空的上下文。

嘗試移動servlet-context.xml直接在WEB-INF/classes之下(即至WEB-INF/classes/servlet-context.xml)。

或者,將其移動到WEB-INF/classes/spring/appServlet/servlet-context.xml,並更改您的代碼classpath*:/spring/appServlet/servlet-context.xml

相關問題