目录
依赖自动装配
概念:IOC容器根据bean所依赖的资源在容器中自动查找并注入到bean中的过程称为自动装配
自动装配的方式:
1.按类型(常用)
2.按名称(有耦合不推荐)
3.按构造方法(不推荐)
4.不启用自动装配
(大前提 就是必须要有个Setter入口,否则会注入失败)
1.按类型(常用)
按类型匹配要求的类型是唯一的否则报错,也就是class一样的只能有一个,并且按类型装配,名字都可以不起(十分推荐,十分解耦)
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl" autowire="byType"/>
2.按名称(还算常用)
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl" autowire="byName"/>
3.依赖自动装配特征
1.自动装配用于引用类型依赖注入,不能对基本类型进行操作
2.使用按类型装配时(byType)必须保障容器中相同类型的bean唯一,推荐使用
3.使用按名称装配时(byName)必须保障容器中具有指定名称的bean因变量名和配置耦合,不推荐使用
4.自动装配优先级低于setter注入与构造器注入,同时出现时会出现自动装配失效
集合注入
常见多种数据注入演示:
数组:
List:
Set:
Map:
Properties:
Spring配置文件
<?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="bookDao" class="com.itheima.dao.impl.BookDaoImpl">
<property name="array">
<array>
<value>100</value>
<value>200</value>
<value>300</value>
</array>
</property>
<property name="list">
<list>
<value>dad</value>
<value>dad</value>
<value>dad</value>
</list>
</property>
<property name="set">
<set>
<value>dad</value>
<value>200</value>
<value>ddd</value>
</set>
</property>
<property name="map">
<map>
<entry key="s" value="s"></entry>
<entry key="w" value="w"></entry>
<entry key="a" value="a"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="www">www</prop>
<prop key="sss">sss</prop>
<prop key="fff">fff</prop>
</props>
</property>
</bean>
</beans>
bookDaoImpl实现类
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import java.util.*;
public class BookDaoImpl implements BookDao {
private int[] array;
private List<String> list;
private Set<String> set;
private Map<String, String> map;
private Properties properties;
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void save() {
System.out.println("bookDao save ...");
System.out.println("array数组:"+ Arrays.toString(array)+"");
System.out.println("list集合:"+list+"");
System.out.println("set集合:"+set+"");
System.out.println("map集合:"+map+"");
System.out.println("properties:"+properties+"");
}
}
效果: