gpt4 book ai didi

spring-boot - 无法在 Spring Boot 中拦截 ApplicationEnvironmentPreparedEvent

转载 作者:行者123 更新时间:2023-12-01 13:23:40 27 4
gpt4 key购买 nike

我需要以编程方式设置一些系统属性,我认为最好的方法是在事件监听器中进行一次 ApplicationEnvironmentPreparedEvent被拦截了。
但问题是我无法在我的听众中捕捉到那个事件。

@Component
public class AppListener {

@EventListener
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
System.setProperty("java.util.concurrent.ForkJoinPool.common.threadFactory", MyThreadFactory.class.getName());
}
}

}

我做错了什么,为什么我不能 catch 那个事件?

最佳答案

来自 Spring Boot documentation :

Some events are actually triggered before the ApplicationContext is created, so you cannot register a listener on those as a @Bean. You can register them with the SpringApplication.addListeners(…​) method or the SpringApplicationBuilder.listeners(…​) method.



来自 Spring documentation (这适用于 5.1.7 版):

Processing of @EventListener annotations is performed via the internal EventListenerMethodProcessor bean which gets registered automatically when using Java config or manually via the or element when using XML config.



所以ApplicationEnvironmentPreparedEvent(以及所有的Spring Boot应用事件)发生在context和bean创建之前,而@EventListener是由bean控制的,所以此时@EventListener注解无法被拾取。您必须专门创建一个监听器类并显式添加它以捕获此事件(或在创建 bean 之前发生的任何事件)。

你的类:
public class AppListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>
{
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event)
{
System.setProperty("java.util.concurrent.ForkJoinPool.common.threadFactory",
MyThreadFactory.class.getName());
}
}

...以及相关的 SpringApplicationBuilder 代码:
ConfigurableApplicationContext context = new SpringApplicationBuilder(Launcher.class)
.listeners(new AppListener()).run();

关于spring-boot - 无法在 Spring Boot 中拦截 ApplicationEnvironmentPreparedEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837173/

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