Spring XML方式配置bean,空指针异常,自动装配使用不当产生的NullPointerException
-
2个类如下
- 异步服务 AsyncService AsyncServiceImp
- 天气服务 WeatherService WeatherServiceImp
-
代码简写如下
public class AsyncServiceImp{
private WeatherService weatherService;
public void setWeatherService(WeatherService weatherService){
this.weatherService = weatherService;
}
}
public class WeatherServiceImp{
some code.....
}
- XML配置
<bean id="asyncService" class="xx.xxx.xx.AsyncServiceImp"/>
<bean id="weatherService " class="xx.xxx.xx.WeatherServiceImp" autowired="byName"/>
项目跑起来之后,AsyncServiceImp类中代码报错NullPointerException,经查证是weatherService空指针。
这时就觉得这个情况很奇怪,明明配置了需要的bean且id也是按照小驼峰原则命名,为何没有自动装配成功。
只看上述2行bean配置不难发现,第1行的bean没有配置autowired=“byName”。因项目beans.xml中的bean众多并没有在意这个地方,且错误的认为bean配置有autowired="byName"意为此bean可自动装配给需要的类,被装配的类bean不必要加autowired=“byName”。事实上这种理解是错误的,autowire = “ByName” 会自动在 beans.xml(容器)的上下文中查找 和自己对象中 set方法 set后面的值对应的 bean 的 id。
按此约定,配置。NPE消失。