在开发中经常会使用 Spring 的@Autowired 来实现对象的自动注入,但是在最近的开发中在多线程中用 Spring 的@Autowired 来自动注入时总是注入不进去,代码如下:Java 代码
package com.common.base.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadRunner implements Runnable{
@Autowired
private ServiceBean serviceBean;
private static AtomicInteger count = new AtomicInteger(0);
@Override
public void run(){
if (serviceBean ==null){
return;
}
serviceBean.log();
count.addAndGet(1);
System.out.println(“当前线程为:” + Thread.currentThread().getName() + “count:” + count);
}
public ServiceBean getServiceBean() {
return serviceBean;
}
public void setServiceBean(ServiceBean serviceBean) {
this.serviceBean = serviceBean;
}
}
其中,ServiceBean 定义如下:Java 代码