Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

Reduction in plumbing code

Before Spring Framework, typical J2EE (or Java EE, as it is called now) applications contained a lot of plumbing code. For example: getting a database connection, exception handling code, transaction management code, logging code, and a lot more.

Let's take a look at a simple example of executing a query using prepared statement:

    PreparedStatement st = null;
try {
st = conn.prepareStatement(INSERT_TODO_QUERY);
st.setString(1, bean.getDescription());
st.setBoolean(2, bean.isDone());
st.execute();
}
catch (SQLException e) {
logger.error("Failed : " + INSERT_TODO_QUERY, e);
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// Ignore - nothing to do..
}
}
}

In the preceding example, there are four lines of business logic and more than 10 lines of plumbing code.

With Spring Framework, the same logic can be applied in a couple of lines:

    jdbcTemplate.update(INSERT_TODO_QUERY, 
bean.getDescription(), bean.isDone());