无法实例化 [org.hibernate.SessionFactory]

Posted

技术标签:

【中文标题】无法实例化 [org.hibernate.SessionFactory]【英文标题】:Failed to instantiate [org.hibernate.SessionFactory] 【发布时间】:2020-08-30 13:10:41 【问题描述】:

我遇到以下异常,有人可以帮忙吗?

org.springframework.beans.factory.BeanCreationException:创建名为“org.springframework.context.event.internalEventListenerProcessor”的bean时出错:bean初始化失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名为 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' 的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在类 com.stixcloud.config.persistence.PersistenceConfig 中创建名称为“sessionFactory”的 bean 时出错:通过工厂方法实例化 bean 失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.hibernate.SessionFactory]:工厂方法'sessionFactory'抛出异常;嵌套异常是 java.lang.NullPointerException 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) 在 org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) 在 org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834) 在 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) 在 org.springframework.context.annotation.AnnotationConfigApplicationContext.(AnnotationConfigApplicationContext.java:84) 在 com.stixcloud.main.StixCloneProductMain.main(StixCloneProductMain.java:30) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:606) 在 org.tanukisoftware.wrapper.WrapperJarApp.run(WrapperJarApp.java:427) 在 java.lang.Thread.run(Thread.java:748) 原因:org.springframework.beans.factory.BeanCreationException:创建名为“org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在类 com.stixcloud.config.persistence.PersistenceConfig 中创建名称为“sessionFactory”的 bean 时出错:通过工厂方法实例化 bean 失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.hibernate.SessionFactory]:工厂方法'sessionFactory'抛出异常;嵌套异常是 java.lang.NullPointerException 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) 在 org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) 在 org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) 在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) 在 org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:201) 在 org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:92) 在 org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101) 在 org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87) 在 org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:69) 在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:330) 在 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:293) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583) 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ... 16 更多 原因:org.springframework.beans.factory.BeanCreationException:在类 com.stixcloud.config.persistence.PersistenceConfig 中创建名称为“sessionFactory”的 bean 时出错:通过工厂方法实例化 bean 失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.hibernate.SessionFactory]:工厂方法'sessionFactory'抛出异常;嵌套异常是 java.lang.NullPointerException 在 org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolv

下面是配置类,我们使用的是spring、hibernate、java wrapper

package com.stixcloud.config.persistence;

import com.stixcloud.service.common.factory.SisticCurrentTenantIdentifierResolver;
import com.stixcloud.service.common.factory.SisticMultiTenantConnectionProvider;
import com.stixcloud.service.common.listener.AuditInterceptor;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true, mode = AdviceMode.PROXY)
@PropertySource(value = "file:/opt/appsconfig/database.properties", ignoreResourceNotFound = true)
public class PersistenceConfig implements TransactionManagementConfigurer 
    Logger logger = Logger.getLogger(PersistenceConfig.class);

    @Autowired
    private Environment environment;

    @Value("$tenant.list")
    private String tenantList;

    public DataSource newDataSource(String jdbcUrl, String jdbcUser, String jdbcPassword) 
        OracleDataSource dataSource = null;
        try 
            dataSource = new OracleDataSource();
            dataSource.setURL(jdbcUrl);
            dataSource.setUser(jdbcUser);
            dataSource.setPassword(jdbcPassword);
         catch (Exception e) 
            logger.error("Error to create common datasource " + e);
            throw new RuntimeException(e);
        
        return dataSource;
    

    @Bean
    public SisticMultiTenantConnectionProvider sisticMultiTenantConnectionProvider() 
        logger.info("Initializing datasource...");
        SisticMultiTenantConnectionProvider connectionProvider = new SisticMultiTenantConnectionProvider();
        Map<String, DataSource> map = new HashMap<String, DataSource>();
        if(StringUtils.isBlank(tenantList)) 
            throw new RuntimeException("No tenants configured in tenant list. Please check jdbc.properties.");
        
        String[] tenants = tenantList.split(",");
        for(String tenantID : tenants) 
            String tenantJdbcUrl = environment.getProperty(tenantID + ".jdbc.url");
            String tenantJdbcUser = environment.getProperty(tenantID + ".jdbc.user");
            String tenantJdbcPassword = environment.getProperty(tenantID + ".jdbc.password");
            DataSource dataSource = this.newDataSource(tenantJdbcUrl, tenantJdbcUser, tenantJdbcPassword);
            map.put(tenantID.toUpperCase(), dataSource);
            logger.info("Datasource initialized for tenant code " + tenantID.toUpperCase());
        
        connectionProvider.setMap(map);
        logger.info("Datasource initialization completed.");
        return connectionProvider;
    

    @Bean
    public SisticCurrentTenantIdentifierResolver currentTenantIdentifierResolver() 
        return new SisticCurrentTenantIdentifierResolver();
    

    @Bean
    public AuditInterceptor auditInterceptor() 
        return new AuditInterceptor();
    

    /**
     * Session factory.
     * 
     * @return the local session factory bean
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    @Bean(name = "sessionFactory")
    public SessionFactory sessionFactory() 
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setPackagesToScan("com.stixcloud.domain");
        sessionFactory.setEntityInterceptor(this.auditInterceptor());

        sessionFactory.getHibernateProperties().put("hibernate.multi_tenant_connection_provider", this.sisticMultiTenantConnectionProvider());
        sessionFactory.getHibernateProperties().put("hibernate.multiTenancy", "DATABASE");
        sessionFactory.getHibernateProperties().put("hibernate.tenant_identifier_resolver", this.currentTenantIdentifierResolver());
        sessionFactory.getHibernateProperties().put("hibernate.show_sql", "false");
        sessionFactory.getHibernateProperties().put("hibernate.format_sql", "false");
        sessionFactory.getHibernateProperties().put("hibernate.dialect", "com.stixcloud.common.dialect.OracleNativeDialect");
        sessionFactory.getHibernateProperties().put("hibernate.jdbc.batch_size", "50");
        sessionFactory.getHibernateProperties().put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
        sessionFactory.getHibernateProperties().put("hibernate.cache.use_query_cache", "false");
        sessionFactory.getHibernateProperties().put("hibernate.cache.use_second_level_cache", "false");
        sessionFactory.getHibernateProperties().put("hibernate.bytecode.use_reflection_optimizer", "true");
        sessionFactory.getHibernateProperties().put("hibernate.connection.SetBigStringTryClob", "true");
        sessionFactory.getHibernateProperties().put("hibernate.jdbc.batch_size", "0");

        try 
            sessionFactory.afterPropertiesSet();
         catch (IOException e) 
            logger.error("Error to create session factory " + e);
            throw new RuntimeException(e);
        

        return sessionFactory.getObject();
    

    @Bean(name = "hbTxManager")
    @DependsOn("sessionFactory")
    public HibernateTransactionManager hibernateTransactionManager() 
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(this.sessionFactory());
        hibernateTransactionManager.setAutodetectDataSource(false);
        return hibernateTransactionManager;
    

    public PlatformTransactionManager annotationDrivenTransactionManager() 
        return this.hibernateTransactionManager();
    

对不起,我看到另一个堆栈跟踪,再次运行时,这是最底层的堆栈跟踪,应该是这个原因

引起:java.lang.NullPointerException 在 org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl.getAnyConnection(AbstractDataSourceBasedMultiTenantConnectionProviderImpl.java:42) 在 org.hibernate.engine.jdbc.internal.JdbcServicesImpl$MultiTenantConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:302) 在 org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124) 在 org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206) 在 org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178) 在 org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843) 在 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928) 在 org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372) 在 org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454) 在 org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439) 在 com.stixcloud.config.persistence.PersistenceConfig.sessionFactory(PersistenceConfig.java:111) 在 com.stixcloud.config.persistence.PersistenceConfig$$EnhancerBySpringCGLIB$$141223b.CGLIB$sessionFactory$4() 在 com.stixcloud.config.persistence.PersistenceConfig$$EnhancerBySpringCGLIB$$141223b$$FastClassBySpringCGLIB$$9f56ffc0.invoke() 在 org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) 在 org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318) 在 com.stixcloud.config.persistence.PersistenceConfig$$EnhancerBySpringCGLIB$$141223b.sessionFactory() 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:606) 在 org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ... 63 更多

【问题讨论】:

分享你的配置类并简要介绍你的技术栈 嗨@YogendraR,刚刚更新了上面的配置类,我们使用的是spring,hibernate,java wrapper 你可以尝试删除 sessionFactory.getObject(),只返回 sessionFactory,并在调用 setSessionFactory() 时使用 sessionFactory().getObject() 并用 @Bean 注释你的 newDataSource() 我试过了,还是一样的异常。 return sessionFactory.getObject() 改为return (SessionFactory) sessionFactory。 hibernateTransactionManager.setSessionFactory(this.sessionFactory()) 更改为 hibernateTransactionManager.setSessionFactory(((LocalSessionFactoryBean) sessionFactory()).getObject())。并用 @Bean 注释 newDataSource() 【参考方案1】:

在您的休眠配置类文件中,您应该正确定义会话对象属性及其方言、数据源和事务管理器,不要忘记用@Bean 注释它们

【讨论】:

我都做了,你建议如何更改上述代码? 嗨,我在上面更新了,我看到另一个堆栈跟踪,再次运行时,这是最底层的堆栈跟踪,这应该是原因...引起:java.lang.NullPointerException at org .hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl.getAnyConnection(AbstractDataSourceBasedMultiTenantConnectionProviderImpl.java:42) 我认为如果你分享你的配置类代码和抛出异常的代码会有帮助

以上是关于无法实例化 [org.hibernate.SessionFactory]的主要内容,如果未能解决你的问题,请参考以下文章

无法实例化页面(net.thucydides.core.webdriver.DriverConfigurationError:无法实例化类 io.appium.java_client.AppiumDr

无法实例化 p5.js 代码(实例模式)

无法实例化 NSManagedObject 的子类

无法在 main() 方法中实例化字段(实例变量)。为啥??爪哇

“无法实例化活动 ComponentInfo”代表啥?

由于以下原因无法实例化模块: