SlandShow
@SlandShow
70% of my body is made of movies.

Почему создание бина выдаёт ошибку?

Пишу Spring-приложение, которое должно взаимодействовать с БД.

У меня есть контекст приложения:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/util
			http://www.springframework.org/schema/util/spring-util.xsd
">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/PersonManager" />
        <property name="username" value="root" />
        <property name="password" value="12345" />
    </bean>

<!-- Проблема с инжектом этого бина :/ -->
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.slandshow" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="database" value="MYSQL" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
            </bean>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="studentDao" class="com.slandshow.dao.StudentDao" />

</beans>


Имею следующие зависимости в pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.slandshow</groupId>
    <artifactId>javaschoolproject</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <properties>
        <spring.framework.version>3.1.3.RELEASE</spring.framework.version>
        <mysql.connector.version>5.1.21</mysql.connector.version>
        <hiberate.version>4.3.5.Final</hiberate.version>
        <hibernate.annotation.version>3.5.6-Final</hibernate.annotation.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>${hibernate.annotation.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hiberate.version}</version>
        </dependency>

    </dependencies>

</project>


И теперь, вот что у меня есть.

DAO:
package com.slandshow.dao;

import com.slandshow.model.Student;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Repository
public class StudentDao implements BaseDao<Student> {
    @PersistenceContext
    protected EntityManager emf;

    public List<Student> findAll(){
        return emf.createQuery("from students").getResultList();
    }
}


package com.slandshow.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;


/*
 * id (INTEGER PRIMARY KEY)
 * name (VARCHAR)
 * class (VARCHAR)
 */

@Entity(name = "students")
@Table(name = "Students")
public class Student implements Serializable {

    @Id
    @Column(name = "id")
    protected long id;

    @Column(name = "name")
    protected String name;

    @Column(name = "class")
    protected String clazz; // class name reserved, so i use clazz...

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

    public void setName(String name) {
        this.name = name;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", name=" + name + ", class=" + clazz + '}';
    }
}


model
package com.slandshow.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;


/*
 * id (INTEGER PRIMARY KEY)
 * name (VARCHAR)
 * class (VARCHAR)
 */

@Entity(name = "students")
@Table(name = "Students")
public class Student implements Serializable {

    @Id
    @Column(name = "id")
    protected long id;

    @Column(name = "name")
    protected String name;

    @Column(name = "class")
    protected String clazz; // class name reserved, so i use clazz...

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

    public void setName(String name) {
        this.name = name;
    }

    public void setClazz(String clazz) {
        this.clazz = clazz;
    }

    @Override
    public String toString() {
        return "Student{" + "id=" + id + ", name=" + name + ", class=" + clazz + '}';
    }
}


И точка входа в приложение:
package com.slandshow;

import com.slandshow.dao.StudentDao;
import com.slandshow.model.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class App {

    public static void main(String... args) {
        ApplicationContext ctx = (ApplicationContext)new ClassPathXmlApplicationContext("app-context.xml");
        StudentDao studentDao = (StudentDao) ctx.getBean("studentDao");
        List<Student> list = studentDao.findAll();

        for (Student student: list) {
            System.out.println(student);
        }
    }
}


При запуске у меня ошибка создания бина emf(лог ниже, но он неполный)

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in class path resource [app-context.xml]: Cannot create inner bean 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#6bdf28bb' of type [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] while setting bean property 'jpaVendorAdapter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#6bdf28bb' defined in class path resource [app-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/internal/CoreMessageLogger
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:282)
	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:121)
....
.........


Не понимаю - что тут не так?
  • Вопрос задан
  • 172 просмотра
Пригласить эксперта
Ответы на вопрос 1
@asmln
В сообщении об ошибке написано:
nested exception is java.lang.NoClassDefFoundError: org/hibernate/internal/CoreMessageLogger

Не найден класс CoreMessageLogger. Скорее всего проблемы с зависимостями. Попробуйте выполнить в maven clean, а затем compile или package. Если не поможет - можно посмотреть дерево зависимостей, может hibernate-core несколько штук подтягивается.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы