This has got me stuck many times, until I found out a workaround. You can use a temporary variable in the static
block, and assign the dataSource
after try-catch
ends using that variable:
private static final DataSource dataSource;
static
{
DataSource tempDataSource = null;
try
{
Context initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:comp/env");
tempDataSource = (DataSource) context.lookup("jdbc/assignment_db");
} catch (NamingException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
dataSource = tempDataSource;
}
However, I would rather not follow normally, and throw the exception from the catch
block only if dataSource
is not initialized, in which case, you won't need a local variable:
static
{
try
{
Context initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:comp/env");
dataSource = (DataSource) context.lookup("jdbc/assignment_db");
} catch (NamingException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
throw new ExceptionInInitializerError("dataSource not initialized");
}
}