简体   繁体   English

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

[英]Injection of autowired dependencies failed while trying to access dao bean

I am getting an error while accessing the web page. 访问网页时出现错误。 here is my code - 这是我的代码-

web.xml file - 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>

dispatcher servlet with name - "dispatcher-servlet.xml" 名称的调度程序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>

Student controller class - 学生控制班-

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 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>

when i mention - this i get an error as "Resource not found". 当我提到-这时,我收到一条错误消息“找不到资源”。 so i tried including all my packages as- 所以我尝试将我所有的包裹都包括在内

 <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>

but then also same result - "Resource not found". 但结果也一样-“找不到资源”。

so only when i give this base-package="com.webProject.controller", then i dont get "Resource not found error", but then it get another error - 因此,仅当我给此base-package =“ com.webProject.controller”时,我才不会收到“找不到资源错误”,但随后又出现另一个错误-

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentController': Injection of autowired dependencies failed; org.springframework.beans.factory.BeanCreationException:创建名称为'studentController'的bean时出错:自动连接依赖项的注入失败;

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.webProject.dao.IStudentDao 嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动连线字段:私有com.webProject.dao.IStudentDao

com.webProject.controller.StudentController.studentDao; com.webProject.controller.StudentController.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching 嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有匹配项

bean of type [com.webProject.dao.IStudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 找到类型为[com.webProject.dao.IStudentDao]的Bean以获得依赖关系:期望至少有1个符合此依赖关系自动候选条件的bean。

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

then i tried to inject the studentDao as , then i also i get an error. 然后我尝试将StudentDao注入,然后我也遇到错误。

I am using Tomcat to deploy this artifact. 我正在使用Tomcat部署此工件。 and using maven to build this project. 并使用Maven构建该项目。 i am not sure how it spring+ hibernate+ maven project works in tomcat? 我不确定spring + hibernate + maven项目在tomcat中如何工作?

I have recently started programming using spring and hibernate and this is my first project using these technologies. 我最近开始使用spring和hibernate进行编程,这是我使用这些技术的第一个项目。 so please pardon me if i am making some basic mistake. 因此,如果我犯了一些基本错误,请原谅我。

can you please help me with some solution. 你能帮我一些解决方案吗?

student 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 interface - 学生dao界面-

package com.webProject.dao;

public interface IStudentDao extends AbstractDao{

}

student dao implementation - 学生道实施-

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;
    }

}

If your DAO classes is placed in different packages with controller classes then you should change your component scan element: 如果将DAO类与控制器类放在不同的包中,则应更改组件扫描元素:

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

Also check that you have annotated your DAO classes with @Repository (or @Component) annotation. 还要检查是否已使用@Repository(或@Component)注释对DAO类进行注释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建bean时出错:自动连接依赖项注入失败; - Error creating bean: Injection of autowired dependencies failed; BeanCreationException:创建名称为&#39;userController&#39;的bean时出错:自动连接依赖项的注入失败 - BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed 创建bean时出错,自动连接依赖项注入失败,无法自动连接字段 - Error creating bean, Injection of autowired dependencies failed, Could not autowire field 创建bean时出错-自动连接依赖项注入失败 - Error creating bean- Injection of autowired dependencies failed 创建名称为&#39;empController&#39;的bean时出错:自动连接的依赖项注入失败 - Error creating bean with name 'empController': Injection of autowired dependencies failed 创建名为“securityConfig”的 bean 时出错:注入自动装配的依赖项失败 - Error creating bean with name 'securityConfig': Injection of autowired dependencies failed 创建名称为&#39;initDbService&#39;的bean时出错:自动连接的依赖项注入失败 - Error creating bean with name 'initDbService': Injection of autowired dependencies failed 创建名称为&#39;reportsController&#39;的bean时出错:自动连接的依赖项注入失败; - Error creating bean with name 'reportsController': Injection of autowired dependencies failed; 创建名称为&#39;employeeController&#39;的bean时出错:自动连接依赖项的注入失败 - Error creating bean with name 'employeeController': Injection of autowired dependencies failed 创建名称为&#39;studentController&#39;的bean时出错:自动连接依赖项的注入失败 - Error creating bean with name 'studentController': Injection of autowired dependencies failed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM