我的xml配置中有以下内容。我想将这些转换为我的代码,因为我正在容器之外进行一些单元/集成测试。
个XML:
<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
是设置的类,那我怎么不能将SqlMapClientFactoryBean
转换为SqlMapClient
答案 0 :(得分:1)
SqlMapClientFactoryBean 是 FactoryBean 。它没有实现SqlMapClient接口本身,而是生成SqlMapClient的实例,这些实例在调用getObject()方法时返回。 Spring容器知道FactoryBeans,并且从调用者的角度看它们看起来就像普通的bean一样。我不确定在容器外部使用FactoryBean是否有效 - 如果在容器生命周期之外调用getObject(),则可能会出现“未初始化”异常...
为什么不为您的测试用例创建一个单独的,剥离的Spring配置,实例化它,并从那里获取bean?或者,您可以使用非Spring方式创建SqlMapClient并在DAO上设置它
答案 1 :(得分:0)
SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean();
factory.setConfigLocation(YOUR_SQL_MAP_CONFIG_RESOURCE);
factory.afterPropertiesSet(); //omitting try/catch code
client = (SqlMapClient)factory.getObject();
瞧
答案 2 :(得分: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();
}