Spring boot multi-threaded @Autowired injection failure solution

Spring boot multi-threaded @Autowired injection failure solution

When dealing with problems in multithreading, beans cannot be injected through @Autowired, and a null pointer exception is reported.

For thread safety, it is anti-injection. If you want to use this class, you can only get an instance from the bean factory. Then we only have to obtain it manually. The
solution is as follows:
This class is a tool class for obtaining beans, and it is also handed over to spring management. It is obtained through the context of the program. In the class that needs to be injected into the bean, use the constructor to call the corresponding method of obtaining the bean to the need. Injection object injection proxy 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);
}

}

Get the use of the bean, get the bean through the class in the construction method

@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;
}

}

Guess you like

Origin blog.csdn.net/qq_42938851/article/details/89175744