Skip to content

Commit

Permalink
Add DataSourceVerifier to check DB connection on startup
Browse files Browse the repository at this point in the history
New class `DataSourceVerifier` created to ensure that the database connection is successfully established when the application context is refreshed. It logs messages indicating the success or failure of this verification.
  • Loading branch information
Gcolon021 committed Aug 26, 2024
1 parent 338f1c3 commit 0c08020
Showing 1 changed file with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package edu.harvard.dbmi.avillach.dictionary.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Service
public class DataSourceVerifier {

private static final Logger LOG = LoggerFactory.getLogger(DataSourceVerifier.class);

private final DataSource dataSource;

@Autowired
public DataSourceVerifier(DataSource dataSource) {
this.dataSource = dataSource;
}

@EventListener(ContextRefreshedEvent.class)
public void verifyDataSourceConnection() {
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
LOG.info("Datasource connection verified successfully.");
} else {
LOG.info("Failed to obtain a connection from the datasource.");
}
} catch (SQLException e) {
LOG.info("Error verifying datasource connection: {}", e.getMessage());
}
}

}

0 comments on commit 0c08020

Please sign in to comment.