尝试访问dao bean时,注入自动连接的依赖项失败 [英] Injection of autowired dependencies failed while trying to access dao bean

查看:1048
本文介绍了尝试访问dao bean时,注入自动连接的依赖项失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问网页时出错。这是我的代码 -



web.xml文件 -

 < ;欢迎-文件列表> 
< 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 =aspectjexpression =com.webProject。*/>
< / context:component-scan>
- >

< bean id =jspViewResolverclass =org.springframework.web.servlet.view.InternalResourceViewResolver>
< property name =viewClassvalue =org.springframework.web.servlet.view.JstlView/>
< property name =prefixvalue =/ WEB-INF / jsp //>
< property name =suffixvalue =。jsp/>
< / bean>

< bean id =mysqlDataSourceclass =org.apache.commons.dbcp.BasicDataSource
destroy-method =close>
< property name =driverClassNamevalue =com.mysql.jdbc.Driver/>
< property name =urlvalue =jdbc:mysql:// localhost:3306 / school/>
< property name =usernamevalue =root/>
< property name =passwordvalue =test/>
< / bean>
< bean id =mySessionFactory
class =org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean>
< property name =dataSourceref =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 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 =hibernateTemplateclass =org.springframework.orm.hibernate3.HibernateTemplate>
< property name =sessionFactoryref =mySessionFactory/>
< / bean>
<! - < bean id =studentDaoclass =com.webProject.dao.StudentDaoImpl>< / bean> - >


< / beans>

学生控制器课程 -

  package com.webProject.controller; 

@Controller
@RequestMapping(/ Student)

公共类StudentController {
@Autowired
private IStudentDao studentDao;
//列表< Student>学生们;

/ * 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,模型模型){
//学生= this.students.get(studentNumber);
学生=(学生)getStudentDao()。load(new Long(studentNumber));
model.addAttribute(学生,学生);
model.addAttribute(studentNumber,Integer.toString(studentNumber));
返回studentDetails;

}

@RequestMapping(value =addStudent,method = RequestMethod.POST)
public String addStudent(@ModelAttribute(student)学生,模型模型){

if(student!= null){
getStudentDao()。save(student);
//this.students.add(student);
model.addAttribute(学生,学生);
model.addAttribute(studentNumber,Integer.toString(getStudentDao()。count()));
返回studentAddSuccess;
} else {
抛出新的NullPointerException();
}
}

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

Student student =新生();
model.addAttribute(学生,学生);

返回studentForm;
}

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

学生=(学生)getStudentDao()。load(new Long(studentNumber));
model.addAttribute(std,student);
getStudentDao()。deleteById(new Long(studentNumber));
返回deleteStudent;

}


}

studentform.jsp

 < body> 
< form:form method =postmodelAttribute =studentaction =addStudent>

< table>

< tr>
< td>学生姓名< / td>
< td>格式:输入路径=studentName< / td>
< / tr>
< tr>
< td>部门< / td>
< td>格式:输入路径=部门< / td>
< / tr>
< tr>
< td> College< / td>
< td>格式:输入路径=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 base-package =com.webProject.dao>< / context:component-scan>
< context:component-scan base-package =com.webProject.model>< / context:component-scan>但后来我也得到相同的资源未找到错误。我尝试了另一种方式中提到的另一种方式 - http://stackoverflow.com/questions/7914363/injection-of-autowired-dependencies-failed
< context:component-scan base-package =com.webProject >
< context:include-filter type =aspectjexpression =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。*;

公共抽象类AbstractHibernateDAOImpl实现AbstractDao {

@Autowired
private HibernateTemplate hibernateTemplate;

public HibernateTemplate getHibernateTemplate(){
return hibernateTemplate;
}

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

protected类domainClass = getDomainClass();

/ **
*返回域对象类的方法
* /
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( );
返回null;
}

});
}

public int count(){
List list = getHibernateTemplate()。find(
select count(*)from+ domainClass.getName() +x);
整数计数=(整数)list.get(0);
返回count.intValue();
}

}

student dao interface -

  package com.webProject.dao; 

公共接口IStudentDao扩展AbstractDao {

}

student dao implementation -

  package com.webProject.dao; 

import org.springframework.stereotype.Repository;

import com.webProject.model.Student;


@Repository(studentDao)
公共类StudentDaoImpl扩展AbstractHibernateDAOImpl实现IStudentDao {


@Override
protected getDomainClass()类$
返回Student.class;
}

}


解决方案

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

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

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


I am getting an error while accessing the web page. here is my code -

web.xml file -

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

    <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

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

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentController': Injection of autowired dependencies failed;

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.webProject.dao.IStudentDao

com.webProject.controller.StudentController.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching

bean of type [com.webProject.dao.IStudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

then i tried to inject the studentDao as , then i also i get an error.

I am using Tomcat to deploy this artifact. and using maven to build this project. i am not sure how it spring+ hibernate+ maven project works in tomcat?

I have recently started programming using spring and hibernate and this is my first project using these technologies. 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 -

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:

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

Also check that you have annotated your DAO classes with @Repository (or @Component) annotation.

这篇关于尝试访问dao bean时,注入自动连接的依赖项失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆