zoukankan      html  css  js  c++  java
  • spring继承注入和自动注入

    1、继承注入

      继承注入分为两种:普通继承注入和抽象继承注入

      1-1、普通继承注入

      普通继承注入,只需要在子类的bean设置parent的属性为父类的bean就可以了

      

    <!--父类bean-->
    <bean id="person" class="com.parentchild.Person"
     p:name="小明" p:age="15">
    </bean>
    <!--子类:设置parent后之类会继承父类的属性-->
    <bean id="man" class="com.parentchild.Man" 
    p:sex="男" parent="person">
    </bean>
    
    <!--也可以不使用parent设置父类bean,被spring管理的子类会自动继承父类的属性
      可以直接在子类中设置父类的属性,如下,但是不推荐-->
    <bean id="man" class="com.parentchild.Man"
    p:sex="男" p:name="小明" p:age="115">
    </bean>

      1-2、抽象继承注入

      抽象父类可以是不存在的,将abstract设置为true,前提是子类需要拥有抽象父类bean中的属性,否则注入失败。

      如果抽象父类是存在的,在父类bean中设置abstract为true就可以了。

    <bean id="myperson" abstract="true">
            <property name="name" value="p1"></property>
            <property name="age" value="2"></property>
    </bean>
    <bean id="man2" class="com.parentchild.Man"
    p:sex
    ="男" parent="myperson">
    </bean>

    2、自动注入

    spring自动注入的bean必须是被spring所管理的bean

    自动导入不能有导入bean的id一样的


    default-autowire-candidates="*dao" 匹配所有以dao结尾的bean
    default-autowire="constructor" 以构造函数匹配
    default-autowire="byName" 以属性名匹配
    default-autowire="byType" 以属性类型匹配
    default-autowire="no" 无
    default-autowire="default" 默认匹配

    在beans中设置

    default-autowire="byType" 自动匹配方式

    default-autowire-candidates="*dao" 自动候选

    意思是:所有的bean都会以byType的自动匹配以dao结尾bean。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-autowire="byType" default-autowire-candidates="*dao">
        <bean id="empdao" class="com.autowire.EmpDaoImpl">
    
        </bean>
    
        <bean id="empservice" class="com.autowire.EmpServiceImpl">
    
        </bean>
    </beans>

    也可以在bean设置autowire只在此bean自动注入

    <bean id="empservice" class="com.autowire.EmpServiceImpl" autowire="byType">
    
    </bean>
  • 相关阅读:
    十八、SAP中使用IF/ELSE判断语句,以及sy-subrc的用法
    十七、SAP中使用SQL语句读取一条数据
    十六、SAP中查看数据库
    十五、SAP自定义结构体
    十四、SAP中定义自定义变量
    十三、SAP中定义变量时赋初始值
    十二、Sap的压缩类型p的使用方法
    十一、SAP文本变量,并设置长度
    十、SAP小数需要用引号括起来
    九、SAP中使用定义时间及使用sy-uzeit取当前时间
  • 原文地址:https://www.cnblogs.com/liweixml/p/11788738.html
Copyright © 2011-2022 走看看