通过在SpringBootServletInitializer主方法中添加以下行,当我将应用程序作为Spring Boot应用程序运行时,我能够启动H2 TCP服务器(文件中的数据库):
@SpringBootApplication
public class NatiaApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
Server.createTcpServer().start();
SpringApplication.run(NatiaApplication.class,args);
}
}
但是如果我在Tomcat上运行WAR文件它不起作用,因为没有调用main方法.在bean初始化之前,如何在应用程序启动时启动H2 TCP服务器有更好的通用方法吗?我使用Flyway(autoconfig),它在“Connection refused:connect”上失败,可能是因为服务器没有运行.谢谢.
最佳答案
这个解决方案适合我.如果应用程序作为Spring Boot应用程序运行,并且如果它在Tomcat上运行,它将启动H2服务器.将H2服务器创建为bean不起作用,因为先前创建了Flyway bean并且“Connection refused”失败了.
原文链接:https://www.f2er.com/spring/432734.html@SpringBootApplication
@Log
public class NatiaApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
startH2Server();
SpringApplication.run(NatiaApplication.class,args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
startH2Server();
return application.sources(NatiaApplication.class);
}
private static void startH2Server() {
try {
Server h2Server = Server.createTcpServer().start();
if (h2Server.isRunning(true)) {
log.info("H2 server was started and is running.");
} else {
throw new RuntimeException("Could not start H2 server.");
}
} catch (sqlException e) {
throw new RuntimeException("Failed to start H2 server: ",e);
}
}
}