在web程序中,由于有struts2提供的插件,我们能够在action中通过get,set方法获取到service的实例,但是在应用程序中,没有struts的插件,而我们又需要用到事务的时候,如何获取到service的实例,为了避免遗忘,特写下此篇博客。
1.配置文件中配置了相应的dao,service
<!-- dao -->
<bean id="holdInfodao" class="com.sseinfo.marginvote.bg.holdinfo.deletehold.dao.HoldInfoDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- service -->
<bean id="holdInfoService" class="com.sseinfo.marginvote.bg.holdinfo.deletehold.service.HoldInfoServiceImpl">
<property name="holdInfodao" ref="holdInfodao"/>
</bean>
2.工具类用来从配置文件中获取到service
package com.sseinfo.marginvote.bg.holdinfo.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringFactoryBean {
private static final ApplicationContext CTX;
static {
String[] paths = {"classpath:applicationContext-beans.xml"};
CTX = new ClassPathXmlApplicationContext(paths);
}
public static Object getBean(String beanName)
{
return CTX.getBean(beanName);
}
}
3.在类中通过工具类获取到service的实例
HoldInfoService holdinfoservice =(HoldInfoService) SpringFactoryBean.getBean("holdInfoService");
holdinfoservice.del(strpara);