gpt4 book ai didi

java - AnnotationConfigApplicationContext 尚未使用 ApplicationContextAware 刷新

转载 作者:行者123 更新时间:2023-11-30 01:59:02 34 4
gpt4 key购买 nike

我在非 Spring 框架中使用 Spring beans,为此我已经实现了 ApplicationContextAware 来访问 spring beans。

@Service
public class ApplicationContextProviderService implements ApplicationContextAware {
private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextProviderService.applicationContext = applicationContext;
}

public static <T> T getBean(Class<T> beanType) {
System.out.println("bean out: " + applicationContext);
return applicationContext.getBean(beanType);
}

}

我尝试从非 Spring 类访问 Spring 服务:ConnectionStateService:

this.connectionStateService = ApplicationContextProviderService.getBean(ConnectionStateService.class);

我收到以下错误:

java.lang.IllegalStateException:
**org.springframework.context.annotation.AnnotationConfigApplicationContext@7f485fda has not been refreshed yet at
** org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1072) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1102) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE] at com.example.app.service.ApplicationContextProviderService.getBean(ApplicationContextProviderService.java:19) ~[classes/:na] at com.example.app.CustomFilter.<init>(CustomFilter.java:26) ~[classes/:na]

如何解决这个问题?

最佳答案

当应用程序在应用程序运行之前尝试调用 ApplicationContext 时,就会出现此问题,因此您将无法拥有应用程序上下文,因为它尚未创建。解决方案是为 ConnectionStateService 类创建一个单例,这样您就不需要创建用于调用 ApplicationContext 的服务。

public class ConnectionStateService { 

// static variable instance of type Singleton
private static ConnectionStateService single_instance = null;

// private constructor restricted to this class itself
private ConnectionStateService() {
// some stuffs for initialize here
}

// static method to create instance of Singleton class
public static ConnectionStateService getInstance() {
if (instance == null)
instance = new ConnectionStateService();
return instance;
}

}

关于java - AnnotationConfigApplicationContext 尚未使用 ApplicationContextAware 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473155/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com