I'm trying to implement the following code in Java EE 8 (Java 11) to access a datasource in Wildfly 20. The objective is to close implicitly the JNDI context and the SQL connection:
try (InitialContext context = new InitialContext();
Connection conn = ((DataSource) context.lookup(pool)).getConnection()) {
// use the connection
}
catch (NamingException e) {
logger.error(e.getMessage());
}
catch (SQLException e) {
logger.error(e.getMessage());
}
Problem is that context is not closeable, as I get the compilation error:
The resource type InitialContext does not implement java.lang.AutoCloseable
I'm trying to avoid adding finally
to close the context, is there a way to achieve this?