多线程时Autowired自动注入问题

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

解决方法:手动获取

package com.zuikc.web.controller;

import com.zuikc.dao.user.bean.User;
import com.zuikc.dao.user.mappers.IUserMapper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/app")
public class GetApplicationController implements ApplicationContextAware {

private static ApplicationContext applicationContext;//springMVC上下文定义
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
GetApplicationController.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return GetApplicationController.applicationContext;
}
public static<T> T getBean(String name)throws BeansException{
return (T)applicationContext.getBean(name);
}

@RequestMapping("getapp")
public String GetAPP(){
IUserMapper userMapper = applicationContext.getBean(IUserMapper.class);
List<User> list = userMapper.GetAll();

String a="11";
return "hello";
/*SpringApplicationContext.getApplicationContext().getBean(CategoryMapper.class)*/
}

}

  

 

  

  




在其他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);

  

原文地址:https://www.cnblogs.com/albertzhangyu/p/9648576.html