前言
原文链接:https://blog.csdn.net/u011493599/article/details/78522315
大家好,我是小徐啊。在Java的多线程开发中,我们使用@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
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(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
UpFinancialContractHandler handler=new UpFinancialContractHandler();
handler.setUser(user);
pool.execute(handler)
总结
以上就是我解决多线程时自动注入失败的方法,感谢你的阅读。
那么,大家还有没有其他好的办法呢?欢迎评论区留言讨论!
如果觉得文章帮到了你,或对文章有疑问,可以关注公众号私信我。
如果有对Java入门开发相关的问题,也可关注我的公众号【Java入门学习】,我会持续更新Java相关的分享!
获取更多资源【软件资源、历年软考真题、核心面试知识、阿里Java开发手册、linux常用命令】,也可关注公众号!
欢迎访问我的个人网站:https://idea-tips.com/