0

我的 xml 配置中有以下内容。我想将这些转换为我的代码,因为我正在容器之外进行一些单元/集成测试。

xmls:

<bean id="MyMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <property name="configLocation" value="classpath:sql-map-config-oracle.xml"/>
  <property name="dataSource" ref="IbatisDataSourceOracle"/>
 </bean>

<bean id="IbatisDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/my/mydb"/>
</bean>

我用来从上面的 xmls 中获取东西的代码:

this.setSqlMapClient((SqlMapClient)ApplicationInitializer.getApplicationContext().getBean("MyMapClient"));

我的代码(用于单元测试):

SqlMapClientFactoryBean bean = new SqlMapClientFactoryBean();
UrlResource urlrc = new UrlResource("file:/data/config.xml");
bean.setConfigLocation(urlrc);
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@123.210.85.56:1522:ORCL");
dataSource.setUsername("dbo_mine");
dataSource.setPassword("dbo_mypwd");
bean.setDataSource(dataSource);

SqlMapClient sql = (SqlMapClient) bean; //code fails here

当使用 xml 时,SqlMapClient是设置的类,那么我为什么不能转换SqlMapClientFactoryBeanSqlMapClient

4

3 回答 3

1

SqlMapClientFactoryBean是一个FactoryBean。它本身并没有实现 SqlMapClient 接口,而是制造了 SqlMapClient 的实例,这些实例在调用它的 getObject() 方法时返回。Spring 容器知道 FactoryBeans,并使它们从调用者的角度看起来就像普通的 bean。我不确定在容器外使用 FactoryBean 是否有效 - 如果您在容器生命周期之外调用 getObject() 可能会收到“未初始化”异常...

为什么不为您的测试用例创建一个单独的、精简的 Spring 配置,实例化它,然后从那里获取 bean?或者,您可以以非 Spring 方式创建 SqlMapClient 并将其设置在您的 DAO

于 2009-11-11T07:44:19.270 回答
0
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
factory.setConfigLocation(YOUR_SQL_MAP_CONFIG_RESOURCE);
factory.afterPropertiesSet(); //omitting try/catch code
client = (SqlMapClient)factory.getObject();

于 2010-05-25T23:11:51.793 回答
0

我想添加对我有用的东西。不得不使用一些遗留代码,直到我可以转换到 MyBatis,我想将旧的 applicationContext xml 转换为 spring @Configuration 类。

@Bean
public SqlMapClient sqlMap() throws Exception
{

    SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
    factory.setConfigLocation(new ClassPathResource("conf/ibatis.xml"));
    DataSource dataSource                   = this.dataSource;
    factory.setDataSource(dataSource);
    factory.afterPropertiesSet();
    return (SqlMapClient) factory.getObject();
}
于 2013-08-10T14:52:13.233 回答