在多线程时使用@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);
原文地址:https://www.cnblogs.com/albertzhangyu/p/9648576.html
时间: 2024-11-13 10:36:24