Java 如果Hibernate数据库连接失败,捕获Grails中的启动异常

Java 如果Hibernate数据库连接失败,捕获Grails中的启动异常,java,spring,hibernate,grails,gorm,Java,Spring,Hibernate,Grails,Gorm,我们正在使用Grails2.0.4、GORM和Hibernate构建一个应用程序。当数据库不可用时,Grails将不会初始化,并且启动失败。我们认为我们的池设置可以防止启动失败,但事实似乎并非如此 如果仅池设置无法解决此问题,是否可以在resources.groovy中捕获异常,如果无法初始化数据库服务,请临时切换到基于文件的服务?像这样的 resources.groovy try{ myDataService(PostgresDatabaseServiceImpl){} }catch

我们正在使用Grails2.0.4、GORM和Hibernate构建一个应用程序。当数据库不可用时,Grails将不会初始化,并且启动失败。我们认为我们的池设置可以防止启动失败,但事实似乎并非如此

如果仅池设置无法解决此问题,是否可以在
resources.groovy
中捕获异常,如果无法初始化数据库服务,请临时切换到基于文件的服务?像这样的

resources.groovy

try{

   myDataService(PostgresDatabaseServiceImpl){}

}catch(Exception e){
   //if database connect failed, use local service instead
   myDataService(FileBasedServiceImpl){}
}
即使上述情况可能发生,也会产生新的问题;如何在数据库可用后动态切换回数据库。我们尝试了上述try/catch,但没有效果,启动问题仍然存在:

创建名为“transactionManagerPostProcessor”的bean时出错: bean的初始化失败

如果仅通过池设置就可以避免启动失败,那么当应用程序尝试使用坏的数据库连接时,我们当然可以在运行时管理SQL异常,但启动失败我们无法管理

DataSource.groovy(池设置)

我们尝试了上述try/catch,但没有效果,启动问题仍然存在:

因此,对于是否可以在
resources.groovy
中为(可能)不可用的数据库注册Springbean的问题,您似乎已经有了答案

或者,您可以尝试在运行时为数据库注册Springbean。这种方法的优点是,即使注册bean失败,您也能够捕获错误并使用基于文件的服务。下面是一个如何在运行时注册数据源bean的示例

要使用这种方法,请在
resources.groovy

myDataService(FileBasedServiceImpl)
然后,当您需要访问数据源时:

class DataSourceService implements ApplicationContextAware {

  def myDataService
  ApplicationContext applicationContext

  private static PG_BEAN = 'postgres'

  def getDataSource() {

    try {
      getPostgresService()

    } catch (ex) {
      myDataService
    }
  }

  private getPostgresService() {
    def postgres

    if (applicationContext.containsBean(PG_BEAN)) {
      postgres = applicationContext.getBean(PG_BEAN)

    } else {
      // register a bean under the name 'postGres' and store a reference to it in postgres
      // https://stackoverflow.com/a/20634968/2648
    }            

    checkPostgres(postgres)
  }

  private checkPostres(postgresBean) {
    // check that the database is available, throw an exception if it's not, return 
    // postgresBean if it is
  }
}

这看起来很有趣,应该可以解决我的问题,我会尝试一下,现在已经很旧了,但我很想听听它是如何工作的。
class DataSourceService implements ApplicationContextAware {

  def myDataService
  ApplicationContext applicationContext

  private static PG_BEAN = 'postgres'

  def getDataSource() {

    try {
      getPostgresService()

    } catch (ex) {
      myDataService
    }
  }

  private getPostgresService() {
    def postgres

    if (applicationContext.containsBean(PG_BEAN)) {
      postgres = applicationContext.getBean(PG_BEAN)

    } else {
      // register a bean under the name 'postGres' and store a reference to it in postgres
      // https://stackoverflow.com/a/20634968/2648
    }            

    checkPostgres(postgres)
  }

  private checkPostres(postgresBean) {
    // check that the database is available, throw an exception if it's not, return 
    // postgresBean if it is
  }
}