调用service报空指针?java.lang.NullPointerException

当在多线程环境中使用非静态成员变量时,如果依赖注入尚未完成或在注入之后的某些代码路径中尝试并发访问这些变量,可能会导致空指针异常。要在多线程环境中安全地使用依赖注入的服务,有几种解决方法:

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管理的线程池,可以确保在多线程环境中安全地使用依赖注入的服务,避免空指针异常。

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋迟言说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值