独立的main方法调用Spring MVC框架中的service

Ctrl层调用service层正常,但是我这边有个需求,需要通过main方法直接调用service层,实现数据库查询。连接池使用的是muBatis,applicationContext.xml中配置了
<bean id="sqlSessionFactory"><property name="mapperLocations">
及dao层中需要注入的Xxx.xml(内为SQL语句)
main方法中我初始化
XxxSercice service = new XxxSerciceImpl();
但是service中的dao为空,请问如何在main中也实现dao的注入?

这个service不能这么new出来,需要在main方法中得到spring容器

public class SpringTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IPersonService ips = (IPersonService) ac.getBean("personService");
ips.sayHelloToSpring();
}
}

,再用容器的getBean(“”)来得到service,这样,是spring容器就把之间的关系都注入好了。这是我写过的一个用main方法做测试的例子。真正的测试是不用main方法的,是用专门的测试工具来模拟web程序的。

追问

你的bean.xml里面是这样吗?
我的applicationContext-core.xml中是遍历包

这种情况也怎么处理?

追答

我使用的是spring的注解@service(‘personService’),没有在bean.xml中配置标签,感觉xml配置好麻烦,要是有一万个bean那xml文件都得写多大。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-20
你这是spring管理bean类,如果直接main方法调用的话,也需要把dao new出来,然后调用service的set方法手动注入进去追问

我的dao接口是IXxxDao.class,实例化是通过spring托管XxxDao.xml进行注入的。
main中如何new dao?

追答

2楼的那个简单些,实例化spring容器,通过getBean方法获取service,这样里面的属性都注入进去了 一段时间没摸spring 了,有点忘了

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网