首页 > 解决方案 > 在 HibernateConfiguration 中使用环境时 ApplicationContext 出错

问题描述

@ServerEndpoint在我的 Spring Boot 应用程序中使用 websockets。这是来自的代码@OnClose

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HibernateConfiguration.class);
UserDetailsService userService = applicationContext.getBean(UserDetailsService.class);  //UserDetailsService is annotated with @Service
String userID = usersref.get(session);
if(userService.checkUserExistence(userID))
    userService.updateLastLogoutTime(userID, new Date());

HibernateConfiguration当凭据被硬编码时,此代码工作正常。我想application.properties使用这样的环境将凭据移动到并读取凭据:

@Autowired
Environment env;

@Bean
public DataSource dataSource()
{
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
    dataSource.setUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.username"));
    dataSource.setPassword(env.getProperty("jdbc.password"));
    return dataSource;
}

开始使用环境后,出现此错误

Error creating bean with name 'dataSource' defined in com.chat.config.HibernateConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalArgumentException: Property 'driverClassName' must not be empty

我还尝试了 DataSourceBuilder:

return DataSourceBuilder
            .create()
            .username(env.getProperty("app.datasource.username"))
            .password(env.getProperty("app.datasource.password"))
            .url(env.getProperty("your URL to database"))
            .driverClassName(env.getProperty("app.datasource.driverClassName"))
            .build();

但是这种方法给出了这个错误

Error creating bean with name 'sessionFactory' defined in com.chat.config.HibernateConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method 'sessionFactory' threw exception; nested exception is java.lang.NullPointerException

我必须指出,除此之外,我所有的服务都工作得很好(包括 JDBC 连接性很好)

有什么解决办法吗?

标签: javaspring-boot

解决方案


推荐阅读