说明:Spring由核心容器IOC降低程序的耦合度(依赖关系),对依赖关系的管理就叫做依赖注入。理解为数据在配置时初始化初值,一般用于数据内容不常修改的情况。如数据库密码等。
注入语法:使用construtor-arg标签
标签位置:bean标签内部
标签中的属性:
type: 用于指定要注入的数据的类型,且该类型是构造函数中某个/些参数类型
index: 用于指定要注入的数据类型
name:用于指定给构造函数中指定名称的参数赋值
==============================以上用于构造函数中参数赋值========================
value:用于提供基本类型和String类型的数据
ref:用于指定其他bean类型数据(在ioc中配置过的bean)
注入的三种数据类型:
a 基本类型和String
b 在配置文件中配置过的bean类型
c 复杂类型/集合类型
三种注入方式:
第一种:使用构造函数提供
<!--student类中无默认构造函数 构造函数为name+age+brithday,需将类成员初始化后才能创建-->
<bean id="student" class="com.lijie.factory.student">
<constructor-arg name="name" value="lijie"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
<constructor-arg name="brithday" value="2019/1/1"></constructor-arg>
</bean>
第二种:使用set方法提供 更常用
前提:bean对象中要存在该注入属性的set方法。
关键标签:property
注入普通数据类型:
<bean id="student1" class="com.lijie.factory.student1">
<property name="age" value="18"></property>
<property name="name" value="李杰"></property>
<property name="brithday" value="2018/4/4"></property>
</bean>
注入复杂数据类型:
用于list结构集合注入的标签:list | array | set
用于Map结构集合注入的标签:map | props
1 <!--使用set方法给复杂类型注入-->
2 <bean id="student2" class="com.lijie.factory.student2">
3 <!--List类型-->
4 <property name="mylist">
5 <list>
6 <value>AAA</value>
7 <value>BBb</value>
8 <value>CCC</value>
9 </list>
10 </property>
11 <property name="myStr">
12 <list>
13 <value>AAA</value>
14 <value>BBb</value>
15 <value>CCC</value>
16 </list>
17 </property>
18 <property name="myMap">
19 <map>
20 <entry key="1" value="数据1"></entry>
21 <entry key="2" value="数据2"></entry>
22 </map>
23 </property>
24 </bean>
第三种:使用注解方法提供
出现位置:在需要注入的变量或方法上。
相当于<property name="" value=""|ref="" ></property>
- @autowrite:在需要注入的数据前添加该注解,spring自动匹配容器中的values的类型并注入。若存在多个匹配值。则匹配容器中的ID值。
- @Qualifier:在@autowrite下方指定名称进行注入,无法单独使用。属性:value:用于指定注入Bean的ID
@Autowired
@Qualifier(value = "helloImpl1")//在@autowrite下方使用@qualifier指定注入对象
Ihello helloImpl=null;
- @Resource:直接按照Bean的id注入,可以单独使用。 属性:name,用于指定注入bean的ID
@Resource(name = "helloImpl1")
Ihello helloImpl=null;
上述三个注入注解(@autowrite @Qualifier @Resource)都只能注入bean类型的,无法注入String和基本类型数据,而复杂类型数据,如数组,map只能由XML文件注入
- @value:用于注入基本类型和String类型,属性:value