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的方法来作为访问路径并不可取,这是可以确定的了.

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