
java 线程类注入问题
在 java 中,线程类无法使用 @autowired 注入依赖项,这是因为线程类不是 spring 管理的 bean。为了解决这个问题,可以使用构造注入的方法。
以下示例代码展示了如何通过构造注入向线程类注入依赖项:
线程类:
立即学习“Java免费学习笔记(深入)”;
public class mythread extends thread {
    private myinterface myinterface;
    private myservice myservice;
    public mythread(myinterface myinterface, myservice myservice) {
        this.myinterface = myinterface;
        this.myservice = myservice;
    }
    @override
    public void run() {
        // 使用注入的依赖项
        ...
    }
}调用:
myinterface myinterface = new myinterfaceimpl(); myservice myservice = new myserviceimpl(); mythread mythread = new mythread(myinterface, myservice); mythread.start();
注入:
在 spring 配置文件中,需要将线程类声明为 bean,并使用构造函数注入依赖项:
<bean id="myThread" class="com.example.mypackage.MyThread">
    <constructor-arg ref="myInterface" />
    <constructor-arg ref="myService" />
</bean>以上就是Java 线程类如何注入依赖项?的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号