依赖注入(dependency injection)
依赖:指bean对象的创建依赖于容器,bean对象的依赖资源。
注入:指bean对象依赖的资源由容器来设置和装配(装配:引用其他已经设置的对象)。
Spring注入(两类)
- 构造器注入(见ioc创建对象);
可通过type,value,name配置,参考Spring的学习1
<bean id="name" class="User">
<constrouctor-arg index="1" value = "你好"></constrouctor-arg>
<bean>
- setter注入,要求被注入的属性必须有set方法。set方法的方法名由set属性首字母大写,如果是boolean,返回没方法,是is。
- 常量注入
<bean id= "student" class="cn.my.vo.Student">
<property name="name" value="哇靠"></property>
</bean>
- bean注入
<bean id="address" class="cn.my.vo.Address">
<property name="address" value="北京"/>
</bean>
<bean id= "student" class="cn.my.vo.Student">
<property name="adr" ref="address"></property>
</bean>
- 数组注入
<bean id= "student" class="cn.my.vo.Student">
<property name="books" >
<!-- 注意array,list,map等为小写 --->
<array>
<value>三国</value>
<value>白夜行</value>
<value>锦衣之下</value>
</array>
</property>
</bean>
- List注入
<bean id= "student" class="cn.my.vo.Student">
<property name="heros" >
<list>
<value>李白</value>
<value>王昭君</value>
<value>瑶</vsalue>
</list>
</property>
</bean>
- Map注入
<bean id= "student" class="cn.my.vo.Student">
<property name="heros" >
<map>
<entrty key="法师" value="小乔"></enerty>
<entry>
<key><value>射手</value></key>
<value>虞姬</value>
</enerty>
</map>
</property>
</bean>
- set注入
<!-- set注入 -->
<property name="games">
<set>
<value>cs</value>
<value>王者</value>
<value>lol</value>
</set>
</property>
- null注入
<!-- null注入 -->
<property name="wife"><null/></property>
- properties注入
<property name="info>
<props>
<prop key="性别">女</prop>
<prop key="身高">190</prop>
</props>
</property >
- p命名空间注入
beans头文件加入xmlns:p=“http://www.springframework.org/schema/p”
<!-- P命名空间注入 属性依然需要set方法 -->
<bean id="user" class="cn.my.vo.User" p:name="撒大晚上" p:age="55"></bean>
- c命名空间注入
1.beans头文件加入 xmlns:c=“http://www.springframework.org/schema/c”
2.要求有对应参数的构造方法
<bean id="user1" class="cn.my.vo.User" c:name="qq" c:age="5"></bean>
来源:CSDN
作者:蠢菜
链接:https://blog.csdn.net/qq_44331582/article/details/104247343