本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

Java线程类如何注入依赖项?

网络教程 app 1℃

Java线程类如何注入依赖项

java 线程类注入问题

在 java 中,线程类无法使用 @autowired 注入依赖项,这是因为线程类不是 spring 管理的 bean。为了解决这个问题,可以使用构造注入的方法。

以下示例代码展示了如何通过构造注入向线程类注入依赖项:

线程类:

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=".example.mypackage.MyThread"> <constructor-arg ref="myInterface" /> <constructor-arg ref="myService" /></bean>

以上就是Java 线程类如何注入依赖项?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Java线程类如何注入依赖项?

喜欢 (0)