zoukankan      html  css  js  c++  java
  • IOC(十一)

    自动装配: 根据指定装配规则(属性名称或属性类型), Spring自动将匹配的属性值进行注入

    实例:

    byName

    创建Department类:

    public class Department {
        @Override
        public String toString() {
            return "Department{}";
        }
    }

    创建Employee类:

    public class Employee {
        private Department dept;
    
        public void setDept(Department dept) {
            this.dept = dept;
        }
    
        @Override
        public String toString() {
            return "Employee{" +
                    "dept=" + dept +
                    '}';
        }
    }

    xml配置:(设置autowire="byName"后bean会自动根据属性名去注入相同id的对象)

    <?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">
    
        <bean id="dept" class="com.ryan.spring5.autowire.Department"></bean>
        <bean id="emp" class="com.ryan.spring5.autowire.Employee" autowire="byName"></bean>
    </beans>

    测试:

    Employee{dept=Department{}}

    byType

    修改xml文件设置: 

    autowire="byType"

    结果相同, 但设置autowire="byType"时, xml中该类型的bean只能有一个, 否则会报错:

  • 相关阅读:
    跨库查询数据
    使用StringBuilder与SqlParameter
    sql 循环 随机数创建数据
    sql like N'%...%' 在C#里的写法
    Html 空格与换行
    Python之随机数
    C#之使用随机数
    C#之ArrayList
    Unity之读取本地图片
    GAN(Generative Adversarial Nets)的发展
  • 原文地址:https://www.cnblogs.com/Ryan368/p/13902481.html
Copyright © 2011-2022 走看看