Java解决多线程无法@Autowired注入,手动获取Bean对象
Java解决多线程无法@Autowired注入,手动获取Bean对象
问题
当我们使用多线程时,又想注入一个service给我们使用,但是我们发现service总是为null。
代码示例:
//例1
public class TaskComments implements Callable<List<String>> {
//注入不进去,总是为null
@Autowired
private RedisClient redisClient;
@Override
public List<String> call() throws Exception {
//业务代码
}
}
//例2
public class TaskComments implements Runnable {
//注入不进去,总是为null
@Autowired
private RedisClient redisClient;
@Override
public void run() {
//业务代码
}
}
原因
new Thread不在spring容器中,也就无法获得spring中的bean对象。
解决方案
1.最简单的方法 把要注入的service通过构造方法传过去
public class TaskComments implements Callable<List<String>> {
private RedisClient redisClient;
private TaskComments(RedisClient redisClient){
this.redisClient = redisClient;
}
@Override
public List<String> call() throws Exception {
//业务代码
}
}
PS:不推荐这样的话有NEW对象了,没有用Spring去管理
2.通过ApplicationContext手动获取Bean(Springboot版本,其他自行百度)
- 1.配置Config
package cn.pconline.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 手动获取Bean
* https://blog.csdn.net/tiger0709/article/details/78270768
* https://blog.csdn.net/u011493599/article/details/78522315
*/
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
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);
}
}
- 2.使用
package cn.pconline.modules.toutiao.task;
import cn.pconline.config.BeanContext;
import cn.pconline.redis.client.RedisClient;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* @Description 多线程无法@Autowired注入,手动获取
* @Author jie.zhao
* @Date 2019/7/24 15:52
*/
@Slf4j
@NoArgsConstructor
public class TaskComments implements Callable<List<String>> {
private RedisClient redisClient = BeanContext.getBean(RedisClient.class);
@Override
public List<String> call() throws Exception {
//业务代码
}
}
-------------已经触及底线 感谢您的阅读-------------