gpt4 book ai didi

java - 如何将ServletContextListener添加到现有的@Service?

转载 作者:行者123 更新时间:2023-12-01 22:05:03 26 4
gpt4 key购买 nike

我有一个现有类,我想添加 ServletContextListener 接口(interface):

@Service
public class MyService {
//...
}

@Component
public class MyController {
@Autowired
private MyService service;
}

这运行得很好。但是,一旦我添加 public class MyService Implements ServletContextListener,我就会在 MyController 上收到以下错误:

org.springframework.beans.factory.BeanCreationException:无法 Autowiring 字段:私有(private)服务。找不到依赖项的 [MyService] 类型的合格 bean:预计至少有 1 个有资格作为此依赖项的 Autowiring 候选者的 bean。依赖注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}。

应用程序在 Tomcat 上运行。我的目标是 @Override public void contextDestroyed() 并在 tomcat 关闭时清理此特定服务内的一些资源。

这里出了什么问题?

最佳答案

由于您想要执行清理任务,因此您应该在 bean 的方法中使用 @PreDestroy:

@Service
public class MyService {
@PreDestroy
public void cleanUp() {
//free resources...
}
}

Spring 应用程序上下文将在 bean 从上下文中销毁之前执行清理任务。

关于java - 如何将ServletContextListener添加到现有的@Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951206/

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