关于Spring的依赖注入问题

今日敲代码遇到个关于spring依赖注入的问题 , 所以来记录一下

     

当程序启动时,web容器会加载spring的配置文件 applicationContext.xml,因为xml文件中配置了 默认包的扫描路径  <context:component-scan base-package="xxxx"> </context:component-scan>,所以此时spring会扫描所有的bean 以及通过注解产生的bean,并通过设置注入或者构造注入来注入该属性的值。


比如一个用于分页的bean,

<pre name="code" class="java">pubic class PageList{
     private JpaTemplate;
     
     public void setJpaTemplate(JpaTe  mplate jpaTemplate) {
		this.jpaTemplate = jpaTemplate;
                System.out.print(this.jpaTemplate);
	}

}


 applicationContext.xml关于PageList的配置如下: 
 

<bean id="pageList" class="com.taoyuan.core.tools.PageList">
	<property name="jpaTemplate" ref="jpaTemplate"/>
</bean>
jpaTemplate和emtityManageFactory均以配置好,这里就不列出来了。


程序启动时做的是:扫描到pageList这个bean,并将jpaTemplate注入给pageList,此时在setter方法中输出jpaTemplate对象是已经实例化了的。。

但是如果你在Controller中重新new PageList();这时的jpaTemplate的值为null,程序用到jpaTemplate的地方则报空指针异常,因为这个pageList是重新new的,spring没有为这个pageList注入jpaTemplate。


解决办法:

在需要用到pageList的Controller中,也用依赖注入的方式来注入pageList.,如:

@Resource(name="pageList")
public PageList pageList;
那么当程序运行时,当扫描model时spring为pageList注入了jpaTemplate,当扫描到Controller时,spring为Controller注入了pageList( 此时的pageList已经被实例化),所以就不会产生 空指针异常 。


这是今日的心得,忘指正。




猜你喜欢

转载自blog.csdn.net/q358543781/article/details/44731381