多线程时Autowired自动注入问题

Posted albertzhangyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程时Autowired自动注入问题相关的知识,希望对你有一定的参考价值。

在多线程时使用@Autowired总是获取不到bean,原因是:new thread不在spring容器中,也就无法获得spring中的bean对象。

解决方法:手动获取

 

package 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 <T> T getBean(String name) throws BeansException {
		return (T)applicationContext.getBean(name);
	}
	
	public static <T> T getBean(Class<T> clz) throws BeansException {
	    return (T)applicationContext.getBean(clz);
	}
}

  

创建thread

 

 

<code class="language-java">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;  
    }  
} 

  

  

 




 

在其他service里调用

 

ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("upFinancial-pool-%d").build();
            ExecutorService pool = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                    6000L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingDeque<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
            UpFinancialContractHandler handler=new UpFinancialContractHandler();
            handler.setUser(user);
            pool.execute(handler);

  



以上是关于多线程时Autowired自动注入问题的主要内容,如果未能解决你的问题,请参考以下文章

解决websocket不能@Autowired注入问题

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

初识Spring源码 -- doResolveDependency | findAutowireCandidates | @Order@Priority调用排序 | @Autowired注入(代码片段

Spring 多线程下注入bean问题详解

jdbcTemplate通过@Autowired自动注入时,值为null的问题

jdbcTemplate通过@Autowired自动注入时,值为null的问题