2016-05-04 19 views
-2

を、私は春の注釈についての問題に会いました。 注釈は@Autowiredです。コードでは@AutowiredCommandControllerクラスの役割を果たしていますが、readVoltageThreadクラスのautowiredの注入が機能しないことがわかりました。readVoltageメソッドを実行すると、NullPointerExceptionのエラーが発生しました。は:今日@Autowired

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

どのように私はそれを修正します。おかげで。

答えて

2

newを使用してReadVoltageThreadを作成すると、Springにはそれに関する知識がなく、つまり@Autowiredを意味し、他のすべての注釈は機能しません。

ReadVoltageThreadは、Springによって管理されるようにautowireする必要がありますが、あなたの設計には他の問題があり、それ以上の修正が必要と思われます。

関連する問題