Spring Boot微服务H2内存数据库销毁方法调用失败,已加参数仍未解决
问题详情
你遇到的警告信息:
2023-10-12T12:26:55.058+05:30 WARN 4228 --- [ionShutdownHook] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLNonTransientConnectionException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL)
当前使用的application.yml配置:
server: port: 8090 spring: datasource: url: jdbc:h2:mem:testdb; driverClassName: org.h2.Driver username: sa password: '' h2: console: enabled: true jpa: database-platform: org.hibernate.dialect.H2Dialect hibernate: ddl-auto: update show-sql: true
解决方案
修正数据库URL参数
你当前的URL末尾多余的分号会导致参数解析异常,同时需要正确添加DB_CLOSE_ON_EXIT=FALSE和DB_CLOSE_DELAY=-1参数,修改后的URL如下:spring: datasource: url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1DB_CLOSE_DELAY=-1会强制H2内存数据库保持连接直到JVM终止,避免应用关闭时数据库提前关闭引发的销毁钩子报错。调整Bean销毁逻辑
如果上述方法无效,可能是Spring默认的inMemoryDatabaseShutdownExecutorBean销毁顺序问题。可以通过排除默认的内存数据库配置类来解决:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.InMemoryDatabaseConfiguration; @SpringBootApplication(exclude = {InMemoryDatabaseConfiguration.class}) public class LoanServiceApplication { public static void main(String[] args) { SpringApplication.run(LoanServiceApplication.class, args); } }验证参数生效
启动应用后,访问H2控制台(默认路径http://localhost:8090/h2-console),使用修改后的数据库URL登录,确认数据库连接正常,数据能正常读写。
内容的提问来源于stack exchange,提问作者Mrinal Gupta

