@Autowire字段具有空指针异常 [未使用"new"关键字]



我已经尝试过为什么我的 Spring @Autowired 字段为空中提到的解决方案? 但问题仍然存在。我尝试用@Configurable @Service注释类DevicePojo(下面的代码(。

这是我的豆子 分发配置.java

@Component
@Configuration
public class DistributionConfig {
@Qualifier("exponentialDistribution")
@Bean
@Scope("prototype")
public DistributionService exponentialDistribution() {
return new ExponentiallyDistribute();
}
@Qualifier("normalDistribution")
@Bean
@Scope("prototype")
public DistributionService normalDistribution() {
return new NormallyDistribute();
}
@Qualifier("uniformDistribution")
@Bean
@Scope("prototype")
public DistributionService uniformDistribution() {
return new UniformlyDistribute();
}
}

JsonFileConfig.java

@Configuration
public class JsonFileConfig {
private static ObjectMapper mapper=new ObjectMapper();
@Qualifier("devicesPojo")
@Bean
public DevicesPojo[] devicesPojo() throws Exception {
DevicesPojo[] devicePojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-devices.json").getFile()),DevicesPojo[].class);
return devicePojo;
}

@Qualifier("linksPojo")
@Bean
public LinksPojo[] linksPojo() throws Exception {
LinksPojo[] linksPojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-adjcies.json").getFile()),LinksPojo[].class);
return linksPojo;
}
}

这是我的设备Pojo,我在其中收到空指针异常。

@JsonDeserialize(using = DeviceDeserializer.class)
@Component
public class DevicesPojo {
private String device;
private List<String> ports;
private List<Integer> bandwidth;
@Autowired
@Qualifier("uniformDistribution")
private DistributionService uniformDistribution; // Here uniformDistribution is null
public DevicesPojo(String device, List<String> port, List<Integer> bandwidth) {
this.device = device;
this.ports= port;
this.bandwidth=bandwidth;
this.uniformDistribution.createUniformDistribution(1000,0,ports.size());
}
public String getDevice(){
return device;
}
public String getRandomPortForDevice()
{
return ports.get((int)uniformDistribution.getSample());
}
public List<String> getAllPorts(){
return ports;
}
public int getBandwidthForPort(String port){    
return bandwidth.get(ports.indexOf(port));
}
}

但是,如果我用private DistributionService uniformDistribution=new UniformDistribution()替换private DistributionService uniformDistribution;,则代码工作正常。

这里有各种各样的问题。
1. 使用 JSON 反序列化程序创建 DevicesPojo 对象。春天没有机会干扰和注入分发服务。
阿拉伯数字。即使它可能会干扰,它也会失败,因为您正在尝试在构造函数中使用"distributionService"对象。字段注入仅在构造对象后才有效。

现在关于解决问题。
长话短说 - 不要指望在您的 POJO 中自动注入。
通常,完全避免动态创建的对象(如DevicesPojo(中的"distributionService"之类的依赖项。
如果您坚持拥有它们,请在施工时手动注入它们:

class DevicesPojoFactory {
@Autowired @Qualifier("uniformDistribution") 
private DistributionService uniformDistribution;
ObjectMapper mapper = new ObjectMapper();
DevicesPojo[] readFromFile(String path) {
DevicesPojo[] devicePojoArr = mapper.readValue(...);
for (DevicesPojo dp: devicePojoArr) {
dp.setDistribution(uniformDistribution);
}
}
}

最新更新