当在多线程环境中使用非静态成员变量时,如果依赖注入尚未完成或在注入之后的某些代码路径中尝试并发访问这些变量,可能会导致空指针异常。要在多线程环境中安全地使用依赖注入的服务,有几种解决方法:
1. 使用静态变量
将 productInfoService
等服务声明为静态变量,并在 @Autowired
注入方法中赋值,这种方式确保在类的静态上下文中可以访问这些服务。
@Component
public class MultiClientServer implements CommandLineRunner {
private static final Log logger = LogFactory.getLog(MultiClientServer.class);
private static RedisUtils redisUtils;
private static LitemallEnvironmentDataService environmentDataService;
private static LitemallProductInfoService productInfoService;
@Autowired
public void setRedisUtils(RedisUtils redisUtils) {
MultiClientServer.redisUtils = redisUtils;
}
@Autowired
public void setEnvironmentDataService(LitemallEnvironmentDataService environmentDataService) {
MultiClientServer.environmentDataService = environmentDataService;
}
@Autowired
public void setProductInfoService(LitemallProductInfoService productInfoService) {
MultiClientServer.productInfoService = productInfoService;
}
@Override
public void run(String... args) {
new Thread(() -> {
testMethod();
}).start();
}
public static void testMethod() {
if (productInfoService != null) {
LitemallProduct product = productInfoService.findRuleId("MN");
logger.info("Product: " + product);
} else {
logger.error("ProductInfoService is not initialized.");
}
}
}
2. 在每个线程中获取Spring上下文
在多线程环境中,可以通过Spring上下文来获取Bean实例。这种方法不需要将服务声明为静态变量,保证线程安全。
@Component
public class MultiClientServer implements CommandLineRunner {
private final Log logger = LogFactory.getLog(MultiClientServer.class);
@Autowired
private ApplicationContext applicationContext;
@Override
public void run(String... args) {
new Thread(() -> {
LitemallProductInfoService productInfoService = applicationContext.getBean(LitemallProductInfoService.class);
testMethod(productInfoService);
}).start();
}
public void testMethod(LitemallProductInfoService productInfoService) {
if (productInfoService != null) {
LitemallProduct product = productInfoService.findRuleId("MN");
logger.info("Product: " + product);
} else {
logger.error("ProductInfoService is not initialized.");
}
}
}
3. 使用依赖注入管理的线程池
确保线程池本身是由Spring管理的Bean,这样可以确保线程池中的线程可以正确访问Spring管理的Bean。
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class MultiClientServer implements CommandLineRunner {
private final Log logger = LogFactory.getLog(MultiClientServer.class);
@Autowired
private LitemallProductInfoService productInfoService;
@Override
public void run(String... args) {
executeAsyncTask();
}
@Async
public void executeAsyncTask() {
testMethod();
}
public void testMethod() {
if (productInfoService != null) {
LitemallProduct product = productInfoService.findRuleId("MN");
logger.info("Product: " + product);
} else {
logger.error("ProductInfoService is not initialized.");
}
}
}
总结
通过将服务声明为静态变量、在每个线程中获取Spring上下文,或者使用Spring管理的线程池,可以确保在多线程环境中安全地使用依赖注入的服务,避免空指针异常。