
在 java 中,线程类往往需要访问其他 bean 的实例。虽然通过 @autowired 自动注入在普通类中很容易实现,但在线程类中却行不通。本文针对 "java 线程类无法注入问题" 提供了详细的解决方法。
线程类与普通类的一个关键区别在于它们不能直接使用 @autowired 注解。这是因为线程类通常不在 spring 容器管理的上下文中运行。
为了解决这个问题,可以使用构造注入。通过在构造函数中显式指定依赖项,可以将所需 bean 传递给线程。
// 线程类
public class mythread implements runnable {
private redistemplate<string, string> redistemplate;
private myinterface myinterface;
public mythread(redistemplate<string, string> redistemplate, myinterface myinterface) {
this.redistemplate = redistemplate;
this.myinterface = myinterface;
}
@override
public void run() {
// 使用 redistemplate 和 myinterface
}
}在调用线程之前,需要使用构造注入将依赖项传递给线程类。
立即学习“Java免费学习笔记(深入)”;
// 调用线程 MyThread myThread = new MyThread(redisTemplate, myInterface); // 启动线程 Thread thread = new Thread(myThread); thread.start();
通过这种方法,在需要进行注入的线程类中就可以正确访问所需的 bean 实例。
以上就是Java 线程类注入难题:如何解决 @Autowired 失效问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号