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文件都得写多大。
我的dao接口是IXxxDao.class,实例化是通过spring托管XxxDao.xml进行注入的。
main中如何new dao?
2楼的那个简单些,实例化spring容器,通过getBean方法获取service,这样里面的属性都注入进去了 一段时间没摸spring 了,有点忘了