在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");
即可