【发布时间】:2017-07-08 08:01:28
【问题描述】:
我已经尝试过Why is my Spring @Autowired field null? 中提到的解决方案,但问题仍然存在。我尝试使用@Configurable @Service 注释类DevicePojo(下面的代码)。
这是我的豆子 DistributionConfig.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;
}
}
这是我的 DevicePojo,我得到空指针异常。
@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; 替换为 private DistributionService uniformDistribution=new UniformDistribution(),则代码可以正常工作。
【问题讨论】:
-
为什么你认为“映射器”应该“尊重”弹簧注释?当您使用
mapper.readValue时,会生成一个new DevicesPojo。一种解决方案是让映射器做他的事情,然后在结果上“设置” DistributionService(DistributionService 你得到一些@Autowired) -
只要我在 DevicePojo 中添加了@Autowired,它就可以正常工作。怎么了?
-
你能详细说明一下吗?某种伪代码会有所帮助。
标签: java spring exception javabeans