在spring中测试的时候,出现如下错误:
Exception in thread "main" java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:153)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:880)
at com.bjsxt.service.UserServiceTest.testAdd(UserServiceTest.java:18)
at com.bjsxt.service.UserServiceTest.main(UserServiceTest.java:26)
源码:
public void testAdd() {
ApplicationContext act = new ClassPathXmlApplicationContext();
UserService service = (UserService) act.getBean("userService");
User u = new User();
u.setUsername("zhangsan");
u.setPassword("pwd");
service.add(u);
}错误提示为:IllegalStateException
这里需要在ClassPathXmlApplicationContext添加一个参数,
把
ApplicationContext act = new ClassPathXmlApplicationContext();改为:
ApplicationContext act = new ClassPathXmlApplicationContext("beans.xml");即可
本文探讨了在使用Spring框架进行测试时遇到的IllegalStateException错误,并提供了具体的解决方案,即在ClassPathXmlApplicationContext中添加参数。通过将ApplicationContext初始化方式从默认改为指定配置文件路径,可以避免此类错误的发生,确保测试过程顺利进行。
546

被折叠的 条评论
为什么被折叠?



