代码如下(为了演示这个报错):
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.getBean("xxx");
报错如下:
Exception in thread "main" java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@20ad9418 has not been refreshed yet
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1032)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1044)
at com.turnx7.spring.iocbyanotation.test.Test.main(Test.java:18)
在使用spring框架使用IOC获取bean时有时可能会碰到这个错误
AnnotationConfigApplicationContext ad has not been refreshed yet
看起来似乎是annotationConfigApplicationContext未刷新的问题,但事实并不是,在添加annotationConfigApplicationContext.refresh();语句后将会出现新的错误
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'defaultCache' available
其实这个问题的本质是beans配置文件并未加载,导致annotationConfigApplicationContext无法获取任何bean信息
解决方法就是在annotationConfigApplicationContext声明时添加配置文件,
AnnotationConfigApplicationContext annotationConfigApplicationContext= new AnnotationConfigApplicationContext(SpringConfig.class);
或者将配置类注册到AnnotationConfigApplicationContext中:
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(SpringConfig.class);
annotationConfigApplicationContext.refresh();
注意是添加Class,即配置类对象
如果是XML方式,则在ClassPathXMLApplicationContext的实例添加XML配置文件即可
欢迎大家私信博主,邀你进技术交流群