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只能有一个, 否则会报错:

  • 相关阅读:
    大batch任务对structured streaming任务影响
    spark 集群优化
    linux神器 strace解析
    打个 hadoop RPC的栗子
    netty 入门
    c#硬件对接数值转换
    RabbitMQ 消息队列入门
    RabbitMQ 开发环境安装部署
    Nginx-4.Nginx如何处理请求
    Nginx-3.控制nginx
  • 原文地址:https://www.cnblogs.com/Ryan368/p/13902481.html
Copyright © 2011-2022 走看看