Controller內注入的Service爲null

這是controller,Service寫好了註解@service,但是調用l /hi/hi 的時候發生空指針異常,按理說IOC容器在初始化testController這個Bean對象的時候就已經注入了 helloSerivce,我查看了beanFactory裏面的所有beanDefination.
沒錯,testController和helloService都在裏面了.

@RestController
@RequestMapping("/hi")
public class TestController {
  public Integer a = 0;
@Autowired
private HelloService helloService;

@RequestMapping("/hi")
private String helloWorld(){
    System.out.println(1);
    return helloService.hello();
}
}

問題出在哪裏呢?當我把private String helloWorld換爲public String helloWorld的時候,helloService成功注入了…
結果就是:調用private方法的時候,注入未開始.
進一步看,我打印a:System.out.println(a++);
這個時候a也爲null.
大致結論:private 方法作爲@RequestMapping,會導致整個類未實例化.

由於

並不知道原理,但是Controller裏使用private的方法來作爲訪問路徑並不可取,這是可以確定的了.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章