Spring的两种注入方式的学习

来源:互联网 发布:人工智能取代的职业 编辑:程序博客网 时间:2024/06/01 09:09

设值注入

  1. xml中bean代码

    一种

    <bean id="goodsService" class="ServiceImp.GoodsServiceImpl"        p:goodsDao-ref="goodsDao" />    <!-- 定义DAO组件,并将SessionFactory注入DAO组件 -->    <bean id="goodsDao" class="DaoImp.GoodsDaoImpl"        p:sessionFactory-ref="sessionFactory" />
 第二种
    <bean id="goodsService" class="ServiceImp.GoodsServiceImpl">        <property name="goodsDao" ref="goodsDao"/>      </bean>    <!-- 定义DAO组件,并将SessionFactory注入DAO组件 -->    <bean id="goodsDao" class="DaoImp.GoodsDaoImpl"        p:sessionFactory-ref="sessionFactory" />

2.在GoodServiceImpl中代码为:

   private  GoodsDao goodsDao   public  void setGoodsDao( GoodsDao goodsDao){     this.goodsDao=goodsDao   }

构造注入
1. 在配置文件中

     <bean id="goodsService" class="ServiceImp.GoodsServiceImpl"        p:goodsDao-ref="goodsDao" >        <constructor-arg name="goodsDao" ref="goodsDao"/>    </bean>

2.在GoodServiceImpl中代码为:

   public  GoodsServiceImpl( GoodsDao goodsDao){     this.goodsDao=goodsDao   }

相对来说,设值注入比较常用些。