zoukankan      html  css  js  c++  java
  • 八、装配bean--自动装配

    一、有时候,我们不想一个一个地去配置一个个ref,希望spring智能一点,让那些对象类型属性自动找到配置文件中同名的,或者类型匹配的bean填充进去。

    public class Employee {
        private String name;
    }
    public class Department {
        private String name;
        private Employee employee;
    }
    <bean id="department" class="com.beans.Department" autowire="byName">
            <property name="name" value="财务部"/>
        </bean>
        
        <bean id="employee" class="com.beans.Employee">
            <property name="name" value="蔡文姬"/>
        </bean>
    autowire="byName"的意思是根据名字自动装配,系统检测到Department有个属性employee没指定值,而有个bean的id又刚好叫employee,就拿来用了。


    二、autowire="byName"同理是根据类型自动装配,bean的id就可以随便了,当然如果xml配置了多个此类型的bean,则没法匹配,会报错
    <bean id="department" class="com.beans.Department" autowire="byType">
            <property name="name" value="财务部"/>
        </bean>
        
        <bean id="xx" class="com.beans.Employee">
            <property name="name" value="蔡文姬"/>
        </bean>

    三、autowire="constructor"的意思就是指i,没配值的属性,系统会去找有没有对应的构造函数

    public class Department {
        private String name;
        private Employee employee;
        
        
        public Department(Employee employee) {//给employee注入值,要求构造函数中,只能这个能给employee注入值
            this.employee = employee;
        }
    <bean id="department" class="com.beans.Department" autowire="constructor">
            <property name="name" value="财务部"/>
        </bean>
        
        <bean id="xx" class="com.beans.Employee">
            <property name="name" value="蔡文姬"/>
        </bean>

    四、autowire="default"

    <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-3.0.xsd"
        default-autowire="byName"
        >
        
        <bean id="department" class="com.beans.Department" autowire="default">
            <property name="name" value="财务部"/>
        </bean>
        
        <bean id="employee" class="com.beans.Employee">
            <property name="name" value="蔡文姬"/>
        </bean>
        
    </beans>
    default-autowire="byName"指定的意思是,以下所有autowire="default"的bean都采用autowire="byName"
  • 相关阅读:
    C++11学习笔记
    孙鑫MFC学习笔记20:Hook编程
    孙鑫MFC学习笔记19:动态链接库
    孙鑫MFC学习笔记18:ActiveX
    孙鑫MFC学习笔记17:进程间通信
    孙鑫MFC学习笔记16:异步套接字
    孙鑫MFC学习笔记:15多线程
    ionic2 使用slides制作滑动效果的类型选择栏
    JavaScript简明教程之Node.js
    ionic2实战-使用Chart.js
  • 原文地址:https://www.cnblogs.com/myz666/p/8207079.html
Copyright © 2011-2022 走看看