尝试访问dao bean时,注入自动连接的依赖项失败

时间:2012-08-15 08:10:28

标签: java spring hibernate tomcat web-applications

我在访问网页时遇到错误。这是我的代码 -

web.xml文件 -

 <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

带名称的调度程序servlet - “dispatcher-servlet.xml”

    <context:annotation-config />
    <context:component-scan base-package="com.webProject.controller"></context:component-scan>
    <!-- <context:component-scan base-package="com.webProject">
        <context:include-filter type="aspectj" expression="com.webProject.*" />
    </context:component-scan>
    -->

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/school" />
        <property name="username" value="root" />
        <property name="password" value="test" />
    </bean>
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="mysqlDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.webProject.model.Student</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="javax.persistence.validation.mode">none</prop>
                <prop key="connection.autocommit">true</prop>
            </props>
        </property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="mySessionFactory" />
    </bean>
    <!-- <bean id="studentDao" class="com.webProject.dao.StudentDaoImpl"></bean>-->


</beans>

学生控制器课程 -

package com.webProject.controller;

@Controller
@RequestMapping("/Student")

public class StudentController {
@Autowired
private IStudentDao studentDao;
//List<Student> students;

/*public StudentController() {
    students = new ArrayList<Student>();
}*/

public IStudentDao getStudentDao() {
    return studentDao;
}

public void setStudentDao(IStudentDao studentDao) {
    this.studentDao = studentDao;
}

@RequestMapping(value="details/{number}",method=RequestMethod.GET)
public String studentDetails(@PathVariable("number") int studentNumber, Model model){
    //Student student = this.students.get(studentNumber);
    Student student = (Student) getStudentDao().load(new Long(studentNumber));
    model.addAttribute("student",student);
    model.addAttribute("studentNumber", Integer.toString(studentNumber));
    return "studentDetails";

}

@RequestMapping(value="addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("student") Student student, Model model){

    if(student != null){
        getStudentDao().save(student);
        //this.students.add(student);
        model.addAttribute("student", student);
        model.addAttribute("studentNumber", Integer.toString(getStudentDao().count()));
        return "studentAddSuccess";
    }else{
        throw new NullPointerException();
    }   
}

@RequestMapping(value="studentRegistration")
public String sendStudentForm(Model model){

    Student student = new Student();
    model.addAttribute("student", student);

    return "studentForm";
}

@RequestMapping(value="delete/{studentNumber}")
public String deleteStudent(@PathVariable("studentNumber") int studentNumber, Model model){

    Student student = (Student) getStudentDao().load(new Long(studentNumber));
    model.addAttribute("std", student);
    getStudentDao().deleteById(new Long(studentNumber));
    return "deleteStudent";

}


}

studentform.jsp

  <body>
    <form:form method="post" modelAttribute="student" action="addStudent">

<table>

    <tr>
        <td>Student Name</td>
        <td>form:input path="studentName"</td>          
    </tr>
    <tr>
        <td>Department</td>
        <td>form:input path="department"</td>
    </tr>
    <tr>
        <td>College</td>
        <td>form:input path="collegeName"</td>
    </tr>
    <tr>
        <td colspan="3"><input type="submit" /></td>
    </tr>

</table>

   </form:form>

</body>

当我提到 -        我得到一个错误,因为“找不到资源”。所以我尝试将我的所有包裹包括在内 -

 <context:component-scan base-package="com.webProject.controller"></context:component-scan>
<context:component-scan base-package="com.webProject.dao"></context:component-scan>
<context:component-scan base-package="com.webProject.model"></context:component-scan> but then also i get same "resource not found" error. i tried another way as mentioned in another thread - http://stackoverflow.com/questions/7914363/injection-of-autowired-dependencies-failed
<context:component-scan base-package="com.webProject">
     <context:include-filter type="aspectj" expression="com.webProject.*" />
</context:component-scan>

然后同样的结果 - “资源未找到”。

所以只有当我给这个base-package =“com.webProject.controller”时,我才会得到“资源未找到错误”,但后来又出现了另一个错误 -

org.springframework.beans.factory.BeanCreationException:创建名为'studentController'的bean时出错:注入自动连接的依赖项失败;

嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.webProject.dao.IStudentDao

com.webProject.controller.StudentController.studentDao;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:无匹配

找到依赖的类型为[com.webProject.dao.IStudentDao]的bean:预期至少有1个bean可以作为此依赖项的autowire候选者。

依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

然后我试着把studentDao注入,然后我也得到了一个错误。

我正在使用Tomcat来部署这个工件。并使用maven来构建这个项目。我不确定spring + hibernate + maven项目在tomcat中是如何工作的?

我最近开始使用spring和hibernate进行编程,这是我使用这些技术的第一个项目。如果我犯了一些基本错误,请原谅我。

你可以帮我解决一下。

学生Dao -

package com.webProject.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.webProject.model.*;

public abstract class AbstractHibernateDAOImpl implements AbstractDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    protected Class domainClass = getDomainClass();

    /**
     * Method to return the class of the domain object
     */
    protected abstract Class getDomainClass();

    @SuppressWarnings("unchecked")
    public PersistentObject load(Long id) {
        return (PersistentObject) getHibernateTemplate().load(domainClass, id);
    }

    public void update(PersistentObject t) {
        getHibernateTemplate().update(t);
    }

    public void save(PersistentObject t) {
        getHibernateTemplate().save(t);
    }

    public void delete(PersistentObject t) {
        getHibernateTemplate().delete(t);
    }

    @SuppressWarnings("unchecked")
    public List<PersistentObject> getList() {
        return (getHibernateTemplate().find("from " + domainClass.getName()
                + " x"));
    }

    public void deleteById(Long id) {
        Object obj = load(id);
        getHibernateTemplate().delete(obj);
    }

    @SuppressWarnings("unchecked")
    public void deleteAll() {
        getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException {
                String hqlDelete = "delete " + domainClass.getName();
                int deletedEntities = session.createQuery(hqlDelete)
                        .executeUpdate();
                return null;
            }

        });
    }

    public int count() {
        List list = getHibernateTemplate().find(
                "select count(*) from " + domainClass.getName() + " x");
        Integer count = (Integer) list.get(0);
        return count.intValue();
    }

}

student dao界面 -

package com.webProject.dao;

public interface IStudentDao extends AbstractDao{

}

学生实施 -

package com.webProject.dao;

import org.springframework.stereotype.Repository;

import com.webProject.model.Student;


@Repository ("studentDao")
public class StudentDaoImpl extends AbstractHibernateDAOImpl implements IStudentDao{


    @Override
    protected Class getDomainClass() {
        return Student.class;
    }

}

1 个答案:

答案 0 :(得分:1)

如果您的DAO类放在具有控制器类的不同包中,那么您应该更改组件扫描元素:

<context:component-scan base-package="com.webProject">

同时检查是否已使用@Repository(或@Component)注释注释了DAO类。