使用Spring,注入Service、Dao时,一般使用单例模式,此时的Service、Dao必须是无状态Bean,即不能含有全局的状态Bean,否则极度危险,在并发时会引起状态混乱。
另:Spring不会对自定义的new Thread进行管理,也即Thread是脱离IOC容器运行。Thread是以多线程方式运行,故Thread中不存在上述的所谓状态Bean共享的问题,当然
如果想在同一线程的不同实例间共享状态,则需要参考另一课题:线程状态共享。有需求的可以去研究下。线程在使用Service、Dao时,是无法通过注入方式注入二者,此时建议
不使用Spring来管理对应的Service和Dao。
ibatis在不使用spring管理时,需要在sqlMapConfig.xml如下配置数据源:
<!--JNDI DataSource for JEE environments -->
<transactionManager type="JDBC" >
<dataSource type="JNDI">
<property name="DataSource" value="java:comp/env/jdbc/tqs"/>
</dataSource>
</transactionManager>
-->
<!-- JDBC -->
<transactionManager type="JDBC" >
<dataSource type="DBCP">
<property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@192.168.5.107:1521:kxone"/>
<property name="JDBC.Username" value="xx"/>
<property name="JDBC.Password" value="xx"/>
</dataSource>
</transactionManager>
使用Spring时,只需要在applicationContext-xx.xml如下配置:
<!-- JNDI DataSource for JEE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/tqs</value>
</property>
</bean>
public class SpringBeanUtil<T>
{
public T getSpringBean(String beanId)
{
//ApplicationContext context = new ClassPathXmlApplicationContext(
// "classpath:/spring/applicationContext.xml");
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:/spring/applicationContext_webservice_sendmt.xml");
//ApplicationContext context_File = new FileSystemXmlApplicationContext(
// "classpath:/spring/applicationContext.xml");
T t = (T)context.getBean(beanId);
return t;
}
//Example
//MoListenerThread moThread = new SpringBeanUtil<MoListenerThread>().getSpringBean("moListenerThread");
public static void main(String[] args)
{
System.out.println( new SpringBeanUtil<SendMtServiceImpl>().getSpringBean("sendMtService"));
}
}