Today, I met a problem about the annotation of spring.
The annotation is @Autowired
. where in the Code, the @Autowired
is play a role in the CommandController
class, but I found the injection of autowired in readVoltageThread
class don't work, and occured error of NullPointerException when run the readVoltage
method.
@Controller
@RequestMapping("/dongjun")
@SessionAttributes("currentUser")
public class CommandController {
@Autowired
private SimpMessagingTemplate template;
@Autowired
public CommandController(SimpMessagingTemplate template) {
this.template = template;
}
@RequestMapping("/read_voltage")
@ResponseBody
public void readVoltage(@RequestParam(required = true) String switchId,
String type) {
ReadVoltageThread readVoltageThread = new ReadVoltageThread(type, switchId, template);
readVoltageThread.setDaemon(true);
readVoltageThread.start();
}
}
class ReadVoltageThread extends Thread {
@Autowired
private HighVoltageCurrentService currentService2;
@Autowired
private HighVoltageVoltageService voltageService2;
@Autowired
public HighVoltageHitchEventService eventService;
private String type;
private String switchId;
private SimpMessagingTemplate template;
public ReadVoltageThread(String type, String switchId, SimpMessagingTemplate template) {
this.type = type;
this.switchId = switchId;
this.template = template;
}
@Override
public void run() {
while(true) {
try {
sleep(5000);
template.convertAndSend("/topic/read_voltage",
readVoltage(type, switchId));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Object readVoltage(String type, String switchId) {
Integer[] deStrings = new Integer[3];
switch (type) {
case "0":break;
case "1"://highVoltage
List<HighVoltageVoltage> cliList2 = voltageService2
.getRecentlyVoltage(switchId, "A");
if (cliList2 != null && cliList2.size() != 0) {
deStrings[0] = cliList2.get(0).getValue();
}
cliList2 = voltageService2
.getRecentlyVoltage(switchId, "B");
if (cliList2 != null && cliList2.size() != 0) {
deStrings[1] = cliList2.get(0).getValue();
}
cliList2 = voltageService2
.getRecentlyVoltage(switchId, "C");
if (cliList2 != null && cliList2.size() != 0) {
deStrings[2] = cliList2.get(0).getValue();
}
break;
case "2":break;
default:
break;
}
return deStrings;
}
}
How I fix it.Thanks.