spring boot多线程@Autowired注入失效解决方案

spring boot多线程@Autowired注入失效解决方案

在多线程处理问题时,无法通过@Autowired注入bean,报空指针异常,

在线程中为了线程安全,是防注入的,如果要用到这个类,只能从bean工厂里拿个实例。那我们只有手动获取,
解决方案如下:
本类是获取bean的工具类,也是交给spring管理,通过程序的上下文获取,在需要注入bean的类中,使用构造方法调用对应获取bean的方法给需要注入对象注入代理bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

/**
 * 上下文对象实例
 */
private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.applicationContext = applicationContext;
}

/**
 * 获取applicationContext
 *
 * @return
 */
public static ApplicationContext getApplicationContext() {
	return applicationContext;
}

/**
 * 通过name获取 Bean.
 *
 * @param name
 * @return
 */
public static Object getBean(String name) {
	return getApplicationContext().getBean(name);
}

/**
 * 通过class获取Bean.
 *
 * @param clazz
 * @param       <T>
 * @return
 */
public static <T> T getBean(Class<T> clazz) {
	return getApplicationContext().getBean(clazz);
}

/**
 * 通过name,以及Clazz返回指定的Bean
 *
 * @param name
 * @param clazz
 * @param       <T>
 * @return
 */
public static <T> T getBean(String name, Class<T> clazz) {
	return getApplicationContext().getBean(name, clazz);
}

}

获取bean的使用,在构造方法中通过class获取bean

@Component
public class CameraThreadService extends Thread {

final NET net = NET.INSTANCE;
int init = net.Net_Init();
private String ip;

private Car_ownerDao dao1;
CameraComponentDaoImpl dao = new CameraComponentDaoImpl();
Camera_infoDaoImpl impl = new Camera_infoDaoImpl();

public CameraThreadService() {

}

public CameraThreadService(String ip1) {
	**dao1 = ApplicationContextProvider.getBean(Car_ownerDao.class);**
	ip = ip1;
}

}

猜你喜欢

转载自blog.csdn.net/qq_42938851/article/details/89175744