Spring XML配置bean,空指针异常,自动装配使用不当产生的NullPointerException

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消失。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值