对于代码@Component public class PaymentSnowFlakeIdGenerator { @Resource private UidSoaGenerateService uidSoaGenerateService; public static PaymentSnowFlakeIdGenerator INSTANCE = new PaymentSnowFlakeIdGenerator(); public long generateId64(){ return uidSoaGenerateService.getId(); } } 当我使用PaymentSnowFlakeIdGenerator.INSTANCE.generateId64()时会报空指针,请帮我修复,并保留这种调用方式。
时间: 2024-02-28 07:51:59 浏览: 67
空指针
首先,需要将 PaymentSnowFlakeIdGenerator 的构造函数私有化,这样就不能直接创建对象了。然后,将 INSTANCE 改为 private,再添加一个静态代码块来初始化 INSTANCE。
修复后的代码如下:
```
@Component
public class PaymentSnowFlakeIdGenerator {
@Resource
private UidSoaGenerateService uidSoaGenerateService;
private static PaymentSnowFlakeIdGenerator INSTANCE;
private PaymentSnowFlakeIdGenerator() {}
static {
INSTANCE = new PaymentSnowFlakeIdGenerator();
}
public static PaymentSnowFlakeIdGenerator getInstance() {
return INSTANCE;
}
public long generateId64() {
return uidSoaGenerateService.getId();
}
}
```
现在,你可以通过 PaymentSnowFlakeIdGenerator.getInstance().generateId64() 来调用 generateId64 方法,而不会再报空指针异常了。
阅读全文