【发布时间】:2018-11-27 22:57:01
【问题描述】:
我在非 Spring 框架中使用 Spring bean,为此我实现了 ApplicationContextAware 来访问 Spring bean。
@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]
如何解决这个问题?
【问题讨论】:
标签: java spring spring-boot