使用Spring手动获得ServiceBean,首先写一个手动获得Spring bean的工具类:
package com.common.base.utils.SpringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 直接通过Spring 上下文获取SpringBean,用于多线程环境
* by jingquan @20160405
*/
public class SpringBeanUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
public static Object getBeanByName(String beanName) {
if (applicationContext == null){
return null;
}
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
}
然后在ThreadRunner类中不自动获取,而是手动获取,代码如下:
package com.common.base.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadRunner implements Runnable{
private ServiceBean serviceBean;
private static AtomicInteger count = new AtomicInteger(0);
public ThreadRunner(){
this.serviceBean = (ServiceBean)SpringBeanUtil.getBeanByName("serviceBean");
}
@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;
}
}