java - 在 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 连接性很好)
有什么解决办法吗?
解决方案
推荐阅读
- javascript - 在Javascript中使用回调函数过滤数组
- algorithm - 大 O 和运行时间?
- python - 如何将以下 R 代码转换为 python
- javascript - 在谷歌浏览器中使用 ESC 键关闭模式类型对话框导致缺乏响应
- twitter - 使用 Retrofit 或 OkHttp 的 Twitter API v2 流式传输
- javascript - JavaScript 类构造函数和 DOM(更新)
- java - 无法打印位于第二个 br 标记中的文本内容
- azure - 当资源在主要位置不可用时,如何将资源部署到 Azure 资源管理器模板中的次要位置?
- spring - 哪个 DI 容器在带有嵌入式 tomcat 的 Spring Boot 上使用?
- google-apps-script - Google 表格 - 时间戳和 clearContent