Spring BeanCreationException关于映射的困惑
问题内容:
试图整合hibernate和春天,我遇到了这个错误
严重:上下文初始化失败
org.springframework.beans.factory.BeanCreationException
:创建名称为’
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
‘的bean时出错:初始化bean失败;嵌套的异常是java.lang.IllegalStateException
:无法将处理程序’
org.me.spring.hib.school.web.SchoolController#0
‘ 映射到URL路径[
/allschools
]:已经org.me.spring.hib.school.web.SchoolController
映射了[class ]
类型的处理程序。
我的控制器看起来像
package org.me.spring.hib.school.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.me.spring.hib.school.dao.SchoolDAO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class SchoolController {
private SchoolDAO schoolDao;
public SchoolDAO getSchoolDao() {
return schoolDao;
}
public void setSchoolDao(SchoolDAO schoolDao) {
this.schoolDao = schoolDao;
}
@RequestMapping("/allschools")
public ModelAndView showAllSchools(HttpServletRequest request,HttpServletResponse response) throws Exception{
if(this.schoolDao ==null){
System.out.println("this.schoolDao is null");
}
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("schoolsList", this.schoolDao.getAllSchools());
return new ModelAndView("allschools", modelMap);
}
}
我已将dao实现注入到应用程序上下文文件中
<context:component-scan base-package="org.me.spring.hib.school.web" />
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" >
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<property name="annotatedClasses">
<list>
<value>org.me.spring.hib.school.domain.School</value>
<value>org.me.spring.hib.school.domain.Teacher</value>
<value>org.me.spring.hib.school.domain.Student</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="schoolDao" class="org.me.spring.hib.school.dao.SchoolDAOImpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean class="org.me.spring.hib.school.web.SchoolController" >
<property name="schoolDao" ref="schoolDao" />
</bean>
我无法弄清为什么 SchoolController#0
被映射到URL。
问题答案:
发生这种情况是因为你们
<context:component-scan base-package="org.me.spring.hib.school.web" />
和
<bean class="org.me.spring.hib.school.web.SchoolController" >
第一行将自动发现并SchoolController
为您注册一个。通过显式声明另一个,您将得到一个副本,并且url映射将发生冲突。
您需要删除<context:component- scan>
,或删除控制器和DAO的显式bean定义。如果执行后者,则需要使用自动装配来注入它们的依赖关系。