为什么 class 实现 Autoclosable 接口的 close 方法比 Sql 连接关闭先被调用?

Why close method of class that implements Autoclosable interface is called first than Sql connection close?

我找到了提交失败时回滚事务的解决方案,并且运行良好。 但是你能解释一下为什么先调用 Autorollback 对象关闭方法而不是关闭连接吗?

自动回滚 class :

public class AutoRollback implements AutoCloseable {
    private Connection conn;
    private boolean committed;
    public AutoRollback(Connection conn){
        this.conn = conn;
    }
    public void commit() throws SQLException {
        conn.commit();
        committed = true;
    }
    @Override
    public void close() throws SQLException {
        if(!committed) {
            conn.rollback();
        }
    }
}

使用自动回滚的服务方法示例:

try(Connection connection = MySQLDAOFactory.getConnection();
            AutoRollback autoRollback = new AutoRollback(connection)){
            result =  carDao.insertCar(connection,car);
            autoRollback.commit();
        } catch (SQLException | NamingException | MySQLEXContainer.MySQLDBExecutionException throwables) {
            throw new ApplicationEXContainer.ApplicationCanNotChangeException(throwables.getMessage(),throwables);
        }

为什么Autorollback的close方法有效?如果连接关闭了怎么调用rollback方法?所以唯一的解释是autorollback close方法在连接关闭之前被调用了,但是为什么呢?

因为这就是 JLS 所说的它必须工作的方式:

A try-with-resources statement is parameterized with variables (known as resources) that are initialized before execution of the try block and closed automatically, in the reverse order from which they were initialized, after execution of the try block.

Source