当前位置: 首页 > 知识库问答 >
问题:

创建在类路径资源中定义了名称为“会话工厂”的bean时出错

宗政子辰
2023-03-14

我的appconfig.class如下所示,用于初始化持久性单元:

package com.myapp;

import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages="com.myapp")
@EnableTransactionManagement
public class AppConfig {

@Bean
public SessionFactory sessionFactory() {
    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
    builder
        .scanPackages("com.myapp.model")
        .addProperties(getHibernateProperties());

    return builder.buildSessionFactory();
}

private Properties getHibernateProperties() {
    Properties prop = new Properties();
    prop.put("hibernate.format_sql", "true");
    prop.put("hibernate.show_sql", "true");
    prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
    return prop;
}

@Bean(name = "dataSource")
public BasicDataSource dataSource() {

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/eventtracker");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

@Bean
public HibernateTransactionManager txManager() {
    return new HibernateTransactionManager(sessionFactory());
}

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new     InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

并抛出异常:

上下文初始化过程中遇到异常-取消刷新尝试:org.springframework.beans.factory.beanCreationException:创建类路径资源[com/myapp/appconfig.class]中定义的名称为“会话工厂”的bean时出错:通过html" target="_blank">工厂方法实例化bean失败;嵌套异常为org.springframework.beans.beanInstantiationException:无法实例化[org.hibernate.sessionFactory]:工厂方法“session Factory”引发异常;嵌套异常为java.lang.NoClassDefoundError:javax/transaction/systemException

共有1个答案

危宜
2023-03-14

看看你最后的例外。

nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException

这意味着类文件javax/transaction/systemexception不在类路径上,因此jvm抱怨noClassDefounderRor

将所有与hibernate相关的jar放在类路径上。

 类似资料: