为什么两个条件有不同的结果:@Autowired

时间:2016-05-04 10:37:57

标签: java spring

今天,我遇到了关于弹簧注释的问题。 注释为@Autowired。在代码中,@AutowiredCommandController类中起作用,但我发现在readVoltageThread类中注入自动装配不起作用,并且发生NullPointerException错误运行readVoltage方法时。

@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;
    }
}

我是如何解决它的。谢谢。

1 个答案:

答案 0 :(得分:2)

当您使用ReadVoltageThread创建new时,Spring对此不了解,这意味着@Autowired并且所有其他注释都无效。

你需要自动装配ReadVoltageThread所以它由Spring管理,虽然我怀疑你的设计还有其他问题,正确的解决方案涉及的远不止这些。