我们有一个SpringApplication,它在默认的ApplicationContext中运行良好,但是我们有一个场景,需要刷新上下文,默认上下文不允许我们这样做。我已经更新了我们的主应用程序类如下:
// package and import lines not shown here but are included in original source
@ComponentScan("edge")
@EnableAutoConfiguration
@Configuration
@EnableTransactionManagement
@EnableAsync
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setApplicationContextClass(AnnotationConfigWebApplicationContext.class);
app.run(args);
}使用此代码,调用app.run(args)将产生以下堆栈跟踪:
Exception in thread "main" java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
at org.springframework.boot.context.event.EventPublishingRunListener.registerApplicationEventMulticaster(EventPublishingRunListener.java:70)
at org.springframework.boot.context.event.EventPublishingRunListener.contextPrepared(EventPublishingRunListener.java:65)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:305)
at edge.server.Application.main(Application.java:43)通过SpringApplication.run(),我注意到上下文的BeanFactory为null。如果删除行app.setApplicationContextClass(AnnotationConfigWebApplicationContext.class),从而将应用程序设置为使用默认上下文,代码将一直运行到我们调用refresh()的点。这一呼吁的结果是:
java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once是否有人以我所描述的方式在AnnotationConfigWebApplicationContext中使用SpringApplication并使其工作?如果是的话,你有什么建议让这件事起作用吗?在调用BeanFactory ()之前,我试图寻找手动创建app.run的方法,但似乎没有任何公共方法可以这样做。谢谢您提供的任何帮助!
需要澄清的编辑:
谢谢你到目前为止的评论和答复。在我最初的文章中,我应该更清楚地了解需要刷新ApplicationContext的场景以及使用AnnotationConfigWebApplicationContext的尝试。我们有一些用于备份和还原目的的服务器启动后运行的代码,这涉及修改我们正在使用的JpaRepositories的内容。我的理解是,在运行这段代码之后,我们需要刷新ApplicationContext,以便再次调用所有init方法。
试图使用默认上下文类(AnnotationConfigEmbeddedWebApplicationContext,(GenericApplicationContext的一个子类)来实现这一点,会抛出我之前提到的IllegalStateException (GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once)。正是这个例外促使我显式地将上下文设置为AnnotationConfigWebApplicationContext,这是AbstractRefreshableApplicationContext的一个子类。我的假设是,为了成功地对刷新方法进行多次调用,我需要应用程序使用AbstractRefreshableApplicationContext。是否有一种方法可以让我上面的代码工作,或者有什么替代方法可以让我们多次刷新上下文?
发布于 2015-06-23 05:41:05
您正在使用Spring,它已经为您做到了这一点,您只是使它变得过于复杂。将类更改为以下内容。
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}并确保它在edge包中,并确保您具有启用web应用程序的spring-boot-starter-web依赖项。没有必要自己处理上下文类。
https://stackoverflow.com/questions/30990885
复制相似问题