IOC操作Bean管理(xml自动装配)
package com.atguigu.spring.autowire;public class Dept {@Overridepublic String toString() {return "Dept{}";}
}
package com.atguigu.spring.autowire;public class Emp {private Dept dept;public void setDept(Dept dept){this.dept = dept;}@Overridepublic String toString() {return "Emp{" +"dept=" + dept +'}';}public void test(){System.out.println(dept);}
}
传统方法:
<?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 = "emp" class = "com.atguigu.spring.autowire.Emp"><property name="dept" ref="dept"></property></bean><bean id = "dept" class = "com.atguigu.spring.autowire.Dept"></bean></beans>
1.什么是自动装配
(1)根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
2.演示自动装配过程
(1)根据属性名称自动注入,注入值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标签属性autowire,配置自动装配autowire属性常用两个值:byName根据属性名称注入,byType根据属性类型注入--><bean id = "emp" class = "com.atguigu.spring.autowire.Emp" autowire="byName"></bean><bean id = "dept" class = "com.atguigu.spring.autowire.Dept"></bean></beans>
(2)根据属性类型自动注入
注意:相同类型不能有多个,不然它不知道注入哪一个
<?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标签属性autowire,配置自动装配autowire属性常用两个值:byName根据属性名称注入,byType根据属性类型注入--><bean id = "emp" class = "com.atguigu.spring.autowire.Emp" autowire="byType"></bean><bean id = "dept" class = "com.atguigu.spring.autowire.Dept"></bean></beans>