有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Bean创建错误

我正在用hibernate和maven学习spring mvc web。但我犯了这个错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.silwal.rentme.daoimpl.PersonDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist

servlet上下文。xml文件在这里

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

    <context:component-scan base-package="com.silwal.rentme,com.silwal.rentme.daoimpl" />


    <!-- DataSource for JDBC connection -->
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </beans:bean>


    <!-- Hibernate 4 SessionFactory Bean -->
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </beans:bean>


    <!-- Transaction Manager to make Transaction Support -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>


     <beans:bean id="personDao" class="com.silwal.rentme.daoimpl.PersonDaoImpl">
        <beans:constructor-arg>
            <beans:ref bean="sessionFactory" />
        </beans:constructor-arg>
    </beans:bean>

这里是数据库关系映射类的Person实体类

package com.silwal.rentme.entity;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person_info")
public class Person {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "middle_name")
    private String middleName;
    @Column(name = "last_name")
    private String lastName;

    public Person() {

    }
    public Person(String firstName,String middleName,String lastName) {
        this.firstName=firstName;
        this.middleName=middleName;
        this.lastName=lastName;
    }
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Override
    public String toString() {
        return "Person[firstName="+firstName+",middleName="+middleName+",lastName="+lastName+"]";
    }

}

这里是PersonDao接口类

  package com.silwal.rentme.dao;
import java.util.List;
import com.silwal.rentme.entity.Person;
public interface PersonDao {
     //List<Person> listAllPerson();
     void savePerson(Person person);
}

PersonDao实现类在这里

package com.silwal.rentme.daoimpl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.silwal.rentme.dao.PersonDao;
import com.silwal.rentme.entity.Person;

@Component
public class PersonDaoImpl implements PersonDao {

    @Autowired
    private SessionFactory sessionFactory;

    public PersonDaoImpl() {

    }
    public PersonDaoImpl(SessionFactory sessionFactory) {
        this.sessionFactory=sessionFactory;
    }

    @Override
    @Transactional
    public void savePerson(Person person) {
        sessionFactory.getCurrentSession().save(person);
    }

}

HomeController课程在这里

package com.silwal.rentme.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.silwal.rentme.daoimpl.PersonDaoImpl;
import com.silwal.rentme.entity.Person;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    @Autowired
     PersonDaoImpl personDao;   
    private Person person;
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        person=new Person("bisho", "", "silwal");
        personDao.savePerson(person);
        return "home";
    }

}

冬眠。cfg。这里是xml类

 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>

        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/rentme</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.show_sql">true</property>
        <property name="hibernate.connection.hbm2ddl.auto">create</property>
        <mapping class="com.silwal.rentme.entity.*" />
    </session-factory>
</hibernate-configuration>

我该怎么解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    只是在冬眠。cfg。WEB-INF文件夹中的xml文件不足以确保它位于类路径上。请看一看有关将此文件放在何处的相关问题:

    Location of hibernate.cfg.xml in project?

    我的建议是创建一个资源文件夹,并将其包含在其中