`

读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);
1
6
分享到:
评论

相关推荐

    spring 2.5.6源码

    XML 配置文件使用 `<bean>` 标签,而注解如 `@Component`、`@Service`、`@Repository` 和 `@Controller` 则用于标记类作为 Spring Bean。 5. **自动扫描**:Spring 2.5.6 引入了组件扫描(Component Scanning),...

    spring2.5.6 jar包+源码

    2.5.6版本是Spring历史上的一个重要里程碑,发布于2009年,虽然现在已经有了更新的版本,但依然在很多项目中被广泛使用。 一、Spring核心概念 1. **依赖注入**:Spring的核心特性之一,允许开发者在运行时通过容器...

    spring-2.5.6源码

    通过深入学习Spring 2.5.6的源码,开发者可以更好地理解Spring的设计哲学,提升解决实际问题的能力,同时也能为升级到更高版本或使用其他Spring相关技术打下坚实基础。在实践中,结合源码和文档,可以对Spring的每一...

    spring2.5.6源码

    rar包内含有spring2.5.6源码,解压即可使用 源代码分析,是一件既痛苦又快乐的事情,看别人写的代码是通过的,但当你能够看明白的时候,相信快乐也会随之而来,为了减少痛苦,更快的带来快乐,在这里希望通过这篇...

    spring2.5.6.zip

    在实际项目中,Spring 2.5.6通常与Maven或Gradle等构建工具结合使用,通过声明依赖来管理jar包。例如,项目中包含的"spring2.5.6"目录下的jar包,如context、beans、aop等,都是Spring框架的核心组成部分,它们共同...

    spring-framework-2.5.6 框架 源码

    spring-framework-2.5.6 框架 源码

    spring2.5.6官方jar包

    spring2.5.6官方jar包 spring2.5.6官方jar包 spring2.5.6官方jar包 spring2.5.6官方jar包 spring2.5.6官方jar包 spring2.5.6官方jar包 spring2.5.6官方jar包

    Spring2.5.6源代码分析(一):IOC容器

    在本篇中,我们将深入探讨Spring框架的核心组件——IoC(Inversion of Control)容器,这是Spring 2.5.6版本的一部分。IoC容器是Spring框架的心脏,它负责管理对象的生命周期和依赖关系,使得开发者能够实现松耦合和...

    spring2.5.6jar包

    Spring 2.5.6是该框架的一个较早版本,发布于2009年,虽然现在已有更新的版本,但在许多遗留系统或对兼容性有特定需求的项目中,它仍然被广泛使用。以下将详细介绍Spring 2.5.6的主要功能和特点: 1. **依赖注入...

    Spring2.5.6开发依赖包最全最好完整版

    通过以上分析,我们可以看出Spring 2.5.6依赖包为开发者提供了一个全面的开发资源库,不仅包括了所有必需的jar文件,还有详尽的文档资料和示例代码,这对于学习和使用Spring框架都是非常有帮助的。

    spring2.5.6注解以及xml简单ioc入门示例

    这个入门示例项目旨在帮助初学者了解和掌握Spring 2.5.6版本中的注解使用和基于XML的IoC配置。 首先,让我们来探讨一下Spring的IoC概念。IoC是一种设计模式,它将对象的创建和管理权交给了容器,而不是由对象自身...

    spring2.5.6源代码及api

    通过对Spring 2.5.6源代码的深入学习,开发者可以更好地理解Spring的设计原则和实现细节,这将有助于在实际项目中更有效地使用Spring框架,并为后续版本的学习打下坚实基础。API文档则提供了关于各个类和方法的详细...

    spring2.5.6开发必备jar包(全)

    Spring框架是Java应用程序开发中的一个核心框架,特别在企业级应用中广泛使用。Spring 2.5.6是该框架的一个稳定版本,发布于2009年,它提供了许多功能,包括依赖注入、面向切面编程、事务管理以及与各种数据库、Web...

    spring2.5.6示例 imagedb

    标题“spring2.5.6示例 imagedb”指的是一个关于Spring框架2.5.6版本的应用实例,其中可能包含了一个名为“imagedb”的数据库管理或图像存储相关的项目。这个实例可能用来演示如何在Spring 2.5.6中配置、管理和操作...

    Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)架包

    一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)  1. jar包引入  Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar  Hibernate 3.6.8:hibernate3.jar...

    spring2.5.6相关依赖jar包

    如果你在项目中使用了Spring 2.5.6,确保正确地引入所有必要的依赖,可以避免类加载错误和缺失功能的问题。 总之,Spring 2.5.6虽然已经相对较老,但它提供的IoC和AOP特性依然强大,且在很多现有的系统中仍发挥着...

Global site tag (gtag.js) - Google Analytics