多线程时Autowired自动注入问题
2021-06-28 20:06
标签:build autowire thread swa builder orm mod 创建 cut 在多线程时使用@Autowired总是获取不到bean,原因是:new thread不在spring容器中,也就无法获得spring中的bean对象。 解决方法:手动获取 创建thread 在其他service里调用 多线程时Autowired自动注入问题 标签:build autowire thread swa builder orm mod 创建 cut 原文地址:https://www.cnblogs.com/albertzhangyu/p/9648576.htmlpackage com.test.configs;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
@SuppressWarnings("unchecked")
public static
package com.test.handler;
import com.test.configs.BeanContext;
import com.test.service.TestService;
import com.test.model.User;
/**
* created by huguoju on 2017/11/13.
*/
public class TestHandler implements Runnable {
private User user;
private TestService testService;
@Override
public void run() {
this.testService= BeanContext.getApplicationContext().getBean(TestService.class);
User user=testService.queryUserById(11);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("upFinancial-pool-%d").build();
ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
6000L, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque