spring set 注入

来源:互联网 发布:盘古网络模板 编辑:程序博客网 时间:2024/06/02 04:51
通常我们托管给spring管理的都是dao service action 这种实现类或者接口 简单说一下set注入方法


注入的方式
方式一
<bean id="billDao" class="com.yaoser.dao.BillDao"/>
<bean id="billService" class="com.yaoser.service.BillService">
    <property name="billDao" ref="billDao"/>
</bean>
<bean></bean>这个标签就是交给spring管理的意思,class里面是你交给spring管理的类的路径。
property ,这个是属性的意思,ref ,即refference,引用。
上面这段可以这么理解,billService里面有一个billDao的属性,它引用了billDao这个id的bean。在调用billService时候里面的billDao也会被关联.
我们的项目是ssh框架的,通常还会注入事务。否则无法对数据库执行删除和修改,并且service里面数据库操作执行失败也不会回滚。
方式二(使用内部bean,但该bean不能被其他bean使用)
<bean id="orderService" class="com.yaoser.service.OrderService">
    <property name="orderDao">
        <bean class="com.yaoser.dao.OrderDao"/>
    </property>
</bean>
与第一种相比,没有ref,即没有引用。写死在orderService的bean里面。假如一个叫BillService的bean想要注入orderDao的话,需要再写一遍orderDao,即:
<bean id="billService" class="com.yaoser.service.BillService">
    <property name="orderDao">
        <bean class="cn.itcast.service.OrderDaoBean"/>
    </property>
</bean>
很罗嗦。
 使用:
(1)
ApplicationContext cxf = new ClasspathXmlApplicationContext("beans.xml");
//容器启动就加载
BillService billService = cxf.getBean("billService");//从配置文件里面拿
Bill bill = new Bill();
billService.add(bill);  
这段代码是调用的代码,从配置文件里面获取bean ,容器启动时候就会加载这些bean, ApplicationContext继承自beanfactory接口,后者是第一次访问才会加载。
ApplicationContext这是一个获取xml上下文的类。我们可以不这么写。
(2)
private Billservice billService; 右键resourse getset 方法。

Bill bill = new Bill();

billService.add(bill);


事务注入:
<bean id="chaOffDateManageDomain" parent="baseTransactionProxy">
      <property name="target">
           <ref local="chaOffDateManageDomainImpl" />
      </property>
 </bean>

  <bean id="chaOffDateManageDomainImpl"    
    class="com.abc.domain.ChaOffDateManageDomainImpl">
          <property name="chaOffDateDao">
               <ref bean="HDAO"/>
          </property>
 </bean>

<bean id="chaOffDateManageService" parent="baseTransactionProxy">
      <property name="target">
           <ref local="chaOffDateManageServiceImpl" />
      </property>
 </bean>
1 0
原创粉丝点击