org.springframework.context.annotation.AnnotationConfigApplicationContext has not been refreshed yet

代码如下(为了演示这个报错):

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配置文件即可

  欢迎大家私信博主,邀你进技术交流群

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值