Spring jpa / Hibernate连接异常

时间:2015-05-07 15:05:45

标签: java spring hibernate spring-jdbc

如果在启动时无法连接到数据库,我希望我的程序退出。目前,此连接使用以下设置进行设置:

应用context.xml中

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>${db.driver}</value>
    </property>
    <property name="url">
        <value>${db.url}</value>
    </property>
    <property name="username">
        <value>${db.username}</value>
    </property>
    <property name="password">
        <value>${db.password}</value>
    </property>
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="packagesToScan" value="com.template" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.ejb.naming_strategy">${naming_strategy}</prop>
            <prop key="hibernate.connection.autoReconnect">true</prop>
            <prop key="hibernate.connection.autoReconnectForPools">true</prop>
            <prop key="hibernate.connection.check-valid-connection-sql">SELECT 1</prop>
            <prop key="hibernate.connection.failOverReadOnly">false</prop>
            <prop key="hibernate.connection.maxReconnects">${maxreconnects}</prop>
            <prop key="hibernate.connection.initialTimeout">${reconnect.interval}</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

存储库:

@Repository
public interface Repository extends CrudRepository<Object, String> {

}

我应该在何处放置代码以捕获由连接失败创建的运行时异常,这一点并不明显。如果数据库不存在,我可以使用任何其他设置退出。

1 个答案:

答案 0 :(得分:1)

通常,如果在启动时无法创建bean,spring将停止。如果DB连接失败,那么无论如何它都会自动停止。你想抓住那个例外,并在退出之前做点什么吗?