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

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

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
程序包org.springframework.context.annotation不存在的问题通常是由于缺少相关的依赖库或者版本不匹配导致的。解决这个问题的方法如下: 1. 确认依赖库:首先,确保你的项目中已经添加了Spring Framework的相关依赖库。可以通过在项目的构建文件(如pom.xml或build.gradle)中添加以下依赖来引入Spring Framework: Maven: ```xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>版本号</version> </dependency> ``` Gradle: ```groovy implementation 'org.springframework:spring-context:版本号' ``` 注意替换"版本号"为你所需的Spring Framework版本。 2. 版本匹配:确保你所使用的Spring Framework版本与你的项目其他组件的版本兼容。如果你使用的是Spring Boot项目,可以通过查看`spring-boot-starter-parent`的版本来确定Spring Framework的版本。 3. 清理和重新构建:如果你已经确认了依赖库和版本都正确,但仍然出现该错误,可以尝试清理和重新构建你的项目。有时候编译过程中可能会出现一些缓存或者临时文件导致依赖无法正确加载。 4. 检查项目配置:确保你的项目配置文件中没有错误或者遗漏。特别是检查是否正确配置了Spring的注解扫描,以及是否正确导入了相关的配置类。 如果以上方法都没有解决你的问题,请提供更多的详细信息,例如你使用的开发工具、项目类型和相关配置,以便我能够更准确地帮助你解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值