• Spring autowire自动装配 ByType和ByName


    不使用自动装配前使用的是类的引用:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="car1" class="cn.Spring.Day15autowire.Car">
            <property name="carname" value="奔驰"></property>
            <property name="carcolor" value="红色"></property>
        </bean>
        <bean id="stu" class="cn.Spring.Day15autowire.Student">
            <property name="name" value="小明"></property>
            <property name="age" value="18"></property>
            <property name="car" ref="car1"></property>
        </bean>
    </beans>

    自动装配有五中模式:

    no   默认的方式是不进行自动装配,通过手工设置ref 属性来进行装配bean
    byName   通过参数名 自动装配,如果一个bean的name 和另外一个bean的 property 相同,就自动装配。
    byType   通过参数的数据类型自动自动装配,如果一个bean的数据类型和另外一个bean的property属性的数据类型兼容,就自动装配
    construct   构造方法中的参数通过byType的形式,自动装配。
    default 由上级标签<beans>的default-autowire属性确定。

     使用自动装配进行注入:

    使用ByType进行装配:

    现在在来一个类使用ByType进行装配:

    报错:因为有两个类型,ByType无法识别到。

     

    使用ByName进行装配:

    ByName依据的是:bean节点的id和类中定义的car名字相同则byName识别。

  • 相关阅读:
    九度OJ 1014:排名 (排序)
    九度OJ 1013:开门人和关门人 (排序)
    九度OJ 1012:畅通工程 (最小生成树)
    Java高级工程师(一)
    FastJson JSON对象及JavaBean之间的相互转换
    webservice 和 RESTful API 接口调用
    [转] jqGrid 属性 事件 合集
    Jqgrid 事件重新设置行数据, 以及 Thymeleaf js下获取model的值
    mybatis配置文件说明--- 注重顺序
    美丽的for循环语句
  • 原文地址:https://www.cnblogs.com/java-263/p/10009420.html
Copyright © 2020-2023  润新知