gpt4 book ai didi

java - Spring中servlet被销毁时如何捕获Configuration类中的回调?

转载 作者:行者123 更新时间:2023-12-02 12:02:45 24 4
gpt4 key购买 nike

我使用的是第 3 方 API,它有两个静态函数:

Manager.start()
Manager.stop()

我创建了一个 spring Configuration 类和相应的启用注释,如下所示:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ManagerConfiguration.class)
@Documented
public @interface ManagerEnable {
}

@Configuration
public class ManagerConfiguration {
static {
Manager.start();
}

// todo: call Manager.stop() when servlet is destroyed
}

用户/客户端可以简单地将@ManagerEnable添加到他们的Configuration类中,一切都可以开箱即用。

我想在主机 servlet 被销毁时捕获回调,这样我就可以调用 Manager.stop()。如何在 ManagerConfiguration 中执行此操作?

请注意,这必须在代码中完成,我不想强​​迫用户/客户端更改其 web.xml 来注册自定义 ServletContextListener。他们应该坚持添加 @ManagerEnable 注释。

最佳答案

根据您项目中使用的 spring 版本,您可以通过这种方式实现它..

Spring 4.2+

class Foo {
@EventListener
public bar(ContextStoppedEvent event) {
}
}

Spring <4.2

class Foo implements ApplicationListener<ContextStoppedEvent> {
void onApplicationEvent(ContextStoppedEvent event);
}

就您而言,我会放弃“静态”方法并使用 ContextRefreshedEvent 事件。

使用的类:

@EventListener (org.springframework.context.event)
ContextClosedEvent (org.springframework.context.event)
ContextRefreshedEvent (org.springframework.context.event)
ContextStoppedEvent (org.springframework.context.event)
ContextStartedEvent (org.springframework.context.event)
ApplicationListener (org.springframework.context)

在这里阅读更多相关内容: https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2

希望有帮助。

关于java - Spring中servlet被销毁时如何捕获Configuration类中的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125176/

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