AnnotationConfigApplicationContext尚未使用ApplicationContextAware刷新

时间:2018-11-25 23:47:55

标签: java spring spring-boot

我在非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]

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

我认为当上下文未初始化时,您正在获取Bean

所以实际上请确保您正在调用这段代码:

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

上下文初始化后

答案 1 :(得分:1)

当应用程序尝试在应用程序运行之前调用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; 
} 

}