近期看同事用idea开发的代码,发现在使用@Autowired的时候,大多使用构造函数进行注入。
以前自己在写代码的时候都是直接在变量上进行注入,也没注意过,查了些资料,发现如果直接在变量上进行注入,那么可能会造成NPE。
构造函数注入的方式:
public class TestController {
private final TestService testService;
@Autowired
public TestController(TestService testService) {
this.testService = testService;
}
…
}
变量注入的方式:
public class TestController {
@Autowired
private TestService testService;
…
}
那么为什么变量注入的方式可能会造成NPE(空指针)?如下:
public class TestController {
@Autowired
private TestService testService;
private String testname;
public TestController(){
this.testname = testService.getTestName();
}
}
这段代码执行时会报NPE。
该类的构造函数中的变量值是通过TestService实例来调用TestService类中的方法获得,而Java类会先执行构造函数,然后在通过@Autowired注入实例,因此在执行构造函数的时候就会报错,因此推荐使用构造函数来注入bean。