依赖注入的本质就是装配,装配是依赖注入的具体行为 依赖注入有两种形式
依赖注入的方式分为以下三种
1. 通过setter注入:
<bean id="user" class="com.pojo.User" name="u3,u4">
<property name="id" value="1"></property>
<property name="name" value="刘德华"></property>
</bean>
2.通过constructor注入
<bean id="user" class="com.pojo.User" name="u3,u4">
<constructor-arg name="id" value="1"></constructor-arg>
<constructor-arg name="name" value="lisi"></constructor-arg>
</bean>
3.通过命名空间注入
首先需要导入约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
<bean id="user" class="com.pojo.User" p:id="18" p:name="17岁那年的雨季">
</bean>
<bean id="user" class="com.pojo.User" c:id="18" c:name="17岁那年的雨季">
</bean>
除此以外,spring还给我们提供了复杂数据类型的依赖注入的方式,以下是全部数据类型的装配方式
public class MixEntity {
private int uuid;
private Integer id;
private String name;
private User user;
private Integer[][] ids;
private List<String> list;
private Set<String> set;
private Map<String, String> map;
private Properties properties;
<util:list id="array">
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
<value>5</value>
</util:list>
<bean id="mixEntity" class="com.pojo.MixEntity" scope="prototype">
<property name="id" value="1"></property>
<property name="name" value="张学友"></property>
<property name="ids">
<list>
<ref bean="array"></ref>
<ref bean="array"></ref>
<ref bean="array"></ref>
<ref bean="array"></ref>
<ref bean="array"></ref>
</list>
</property>
<property name="list">
<list>
<value>郭达</value>
<value>黎明</value>
<value>蔡徐坤</value>
<value>哥哥</value>
<value>妹妹</value>
</list>
</property>
<property name="map">
<map>
<entry key="age" value="18"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="name">张学友</prop>
</props>
</property>
</bean>
对于二维数组的注入,需要使用ref标签来引用
上述方式都是通过手动的方式进行的依赖注入,而spring为开发人员提供了自动装配的方式
1.在xml中使用autowird进行自动装配
public class Human {
private Head head;
private Body body;
private Arm arm;
private Leg leg;
}
<bean id="human" class="com.pojo.Human" autowire="byType"></bean>
可以通过类型和name进行自动装配
2.通过autowired注解自动装配
需要先配置xml允许配置注解,否则注解无法生效
<context:annotation-config></context:annotation-config>
public class Human {
@Autowired
private Head head;
@Autowired
private Body body;
@Autowired
private Arm arm;
@Autowired
private Leg leg;
@Override
public String toString() {
return "Human{" +
"head=" + head +
", body=" + body +
", arm=" + arm +
", leg=" + leg +
'}';
}
}
Autowired是通过类型进行的自动装配,因此在以下场景会抛出异常
<bean id="leg11" class="com.pojo.Leg"></bean>
<bean id="leg22" class="com.pojo.Leg"></bean>
要通过名称自动装配需要搭配
@Autowired
@Qualifier("leg11")
private Leg leg;
虽然是通过类型进行的装配,但是假如bean 的id和属性值一致时,即使存在多个相同的类型也不会报错,这说明新版的Autowired也可以根据name装配
3.使用Resource装配则与Autowired相反,先通过name装配再通过类型装配