读Spring 2.5.6 源码学匿名类的使用

  最近开始重新学习spring。在研究spring开发包自带的例子jpetstore时,遇到了匿名类的使用,感觉新鲜,于是择其一二处,以供日后反刍。
  在 org.springframework.orm.ibatis 包中,有一个类叫SqlMapClientTemplate,它是用spring整合iBatis对数据库进行操作的一个工具类。浏览一下,其主要提供了对数据库的各种“增查改删”的操作。



public Object insert(String statementName) throws DataAccessException {
	return insert(statementName, null);
}

public Object insert(final String statementName, final Object   parameterObject) throws DataAccessException {

return execute(new SqlMapClientCallback() {
public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
	return executor.insert(statementName, parameterObject);
	}});
}



public List queryForList(String statementName) throws DataAccessException {
		return queryForList(statementName, null);
	}

	public List queryForList(final String statementName, final Object parameterObject)
			throws DataAccessException {

		return executeWithListResult(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				return executor.queryForList(statementName, parameterObject);
			}
		});
	}



public int update(String statementName) throws DataAccessException {
		return update(statementName, null);
	}

	public int update(final String statementName, final Object parameterObject)
			throws DataAccessException {

		Integer result = (Integer) execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				return new Integer(executor.update(statementName, parameterObject));
			}
		});
		return result.intValue();
	}



public int delete(String statementName) throws DataAccessException {
		return delete(statementName, null);
	}

	public int delete(final String statementName, final Object parameterObject)
			throws DataAccessException {

		Integer result = (Integer) execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				return new Integer(executor.delete(statementName, parameterObject));
			}
		});
		return result.intValue();
	}




从以上诸方法可以看出,在spring中使用了匿名类,使这一经典框架代码更加简洁美观。如果仅仅是代码的简洁美观,不能用,那就这样煞费苦心的设计就成了花拳绣腿了。我们可以注意到,以上所有的代码中所有的匿名类都实现了一个接口,那就是同一包(org.springframework.orm.ibatis)下的SqlMapClientCallback。这个接口只有一个方法,
Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException;

上述匿名类实现了这一接口,重写了上述方法。 之后工具类SqlMapClientTemplate利用
public Object execute(SqlMapClientCallback action) throws DataAccessException

调用了匿名类实现的接口方法 doInSqlMapClient。代码如下:
public Object execute(SqlMapClientCallback action) throws DataAccessException {
		Assert.notNull(action, "Callback object must not be null");
		Assert.notNull(this.sqlMapClient, "No SqlMapClient specified");

		// We always needs to use a SqlMapSession, as we need to pass a Spring-managed
		// Connection (potentially transactional) in. This shouldn't be necessary if
		// we run against a TransactionAwareDataSourceProxy underneath, but unfortunately
		// we still need it to make iBATIS batch execution work properly: If iBATIS
		// doesn't recognize an existing transaction, it automatically executes the
		// batch for every single statement...

		SqlMapSession session = this.sqlMapClient.openSession();
		if (logger.isDebugEnabled()) {
			logger.debug("Opened SqlMapSession [" + session + "] for iBATIS operation");
		}
		Connection ibatisCon = null;

		try {
			Connection springCon = null;
			DataSource dataSource = getDataSource();
			boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);

			// Obtain JDBC Connection to operate on...
			try {
				ibatisCon = session.getCurrentConnection();
				if (ibatisCon == null) {
					springCon = (transactionAware ?
							dataSource.getConnection() : DataSourceUtils.doGetConnection(dataSource));
					session.setUserConnection(springCon);
					if (logger.isDebugEnabled()) {
						logger.debug("Obtained JDBC Connection [" + springCon + "] for iBATIS operation");
					}
				}
				else {
					if (logger.isDebugEnabled()) {
						logger.debug("Reusing JDBC Connection [" + ibatisCon + "] for iBATIS operation");
					}
				}
			}
			catch (SQLException ex) {
				throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
			}

			// Execute given callback...
			try {
				return action.doInSqlMapClient(session);
			}
			catch (SQLException ex) {
				throw getExceptionTranslator().translate("SqlMapClient operation", null, ex);
			}
			finally {
				try {
					if (springCon != null) {
						if (transactionAware) {
							springCon.close();
						}
						else {
							DataSourceUtils.doReleaseConnection(springCon, dataSource);
						}
					}
				}
				catch (Throwable ex) {
					logger.debug("Could not close JDBC Connection", ex);
				}
			}

			// Processing finished - potentially session still to be closed.
		}
		finally {
			// Only close SqlMapSession if we know we've actually opened it
			// at the present level.
			if (ibatisCon == null) {
				session.close();
			}
		}
	}

注意此段代码中46行return action.doInSqlMapClient(session);

你可能感兴趣的:(spring,框架,jdbc,orm,ibatis)