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>
  • 相关阅读:
    【HDU 4305】Lightning(生成树计数)
    【HDU 1150】Machine Schedule(二分图匹配)
    【HDU 2063】过山车(二分图匹配)
    透过Nim游戏浅谈博弈
    [SCOI2010]字符串
    [SCOI2010]传送带[三分]
    [SCOI2010]序列操作[分块or线段树]
    HDU 5306 Gorgeous Sequence[线段树区间最值操作]
    1455: 罗马游戏[左偏树or可并堆]
    Codevs 5914 [SXOI2016]最大值
  • 原文地址:https://www.cnblogs.com/liweixml/p/11788738.html
Copyright © 2011-2022 走看看