Bean的简单依赖注入
所谓的简单依赖:基本数据类型及其包装类型、 String类型、其它Bean实例。
通过构造方法参数
<!--
1. 要想让Spring 放入 其它Bean ,意味着 “那个bean” 也需要被Spring 所管理。
-->
<bean id="otherBean" class="com.example.spring.di.simple.OtherBean"/>
<!--
2. 下面演示在 XML 中如何进行构造方法的注入
-->
<bean name="bean1" class="com.example.spring.di.simple.Bean1">
<!--
对于构造方法的注入,可以在这里使用子标签 constructor-arg
它的name属性: 用于指定构造方法的形参的名字
如果它的值是一个简单类型,使用value属性来指定。
如果它的值是一个其它的bean,使用ref属性来指定。
-->
<constructor-arg name="prop1" value="200"/> <!--这个数字100 会自动对应到 int类型上-->
<constructor-arg name="prop2" value="3.14"/> <!--这个数字3.14 会自动对应到 double类型上 -->
<constructor-arg name="prop3" value="hello world"/> <!--字符串的值 也会对应到 String 类型上-->
<constructor-arg name="otherBean" ref="otherBean" /> <!--ref的属性值,是容器中其他对应类型bean的名字-->
<constructor-arg name="prop4" value="true"/> <!--字符串的true、false 也能自动对应到boolean类型上-->
</bean>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vk7atcZT-1600239656405)(imges/image-20200825175523827.png)]
针对上面配置复杂的情况,Spring也提供了简化的配置方式 通过 c名称空间
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0ViAPeNJ-1600239656408)(imges/image-20200825175657703.png)]
<bean name="bean1" class="com.example.spring.di.simple.Bean1" c:prop1="200"
c:prop2="3.14" c:prop3="hello world" c:otherBean-ref="otherBean" c:prop4="false"/>
通过setter方法
<!--
1. 要想让Spring 放入 其它Bean ,意味着 “那个bean” 也需要被Spring 所管理。
-->
<bean id="otherBean" class="com.example.spring.di.simple.OtherBean"/>
<!--2. 通过setter方法来进行注入
使用 property 子标签来进行设置
后面的规则跟之前一直。
name 属性值 对应的是 setter方法对应的 属性名
如果对应的值是简单类型,就用 value属性。
如果对应的值是其它bean,就用 ref 属性。
-->
<bean id="bean2" class="com.example.spring.di.simple.Bean2">
<property name="prop1" value="200"/> <!--这个数字100 会自动对应到 int类型上-->
<property name="prop2" value="3.14"/> <!--这个数字3.14 会自动对应到 double类型上 -->
<property name="prop3" value="hello world"/> <!--字符串的值 也会对应到 String 类型上-->
<property name="otherBean" ref="otherBean" /> <!--ref的属性值,是容器中其他对应类型bean的名字-->
<property name="prop4" value="true"/> <!--字符串的true、false 也能自动对应到boolean类型上-->
</bean>
同理,为了简化setter的注入,Spring也提供了 p 名称空间:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y4iz9IH5-1600239656410)(imges/image-20200825180729834.png)]
<bean id="bean2" class="com.example.spring.di.simple.Bean2" p:prop1="200"
p:prop2="3.14" p:prop4="true" p:otherBean-ref="otherBean" p:prop3="hello"/>