码迷,mamicode.com
首页 > 编程语言 > 详细

Spring学习笔记四

时间:2016-02-29 16:28:14      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

spring注入参数详解

  在Spring配置文件中, 用户不但可以将String, int等字面值注入到Bean中, 还可以将集合, Map等类型的数据注入到Bean中, 此外还可以注入配置文件中定义的其他Bean.

1.字面值

  "字面值"一般是指可用字符串表示的值, 这些值可通过<value>元素标签进行注入. 基本数据类型及其封装类, String等类型都可以采用字面值注入的方式.

  注入字面值:

 <bean id="car" class="com.attr.Car">
        <property name="brand" value="奥迪"/>
        <property name="color" value="黑色"/>
        <property name="maxSpeed" value="300"/>
   </bean>

2.引用其他Bean

  Spring IoC容器中定义的Bean可以相互引用. 例如Boss类中拥有一个Car类型的属性.

public class Boss {
   private Car car;
   
   public void setCar(Car car) {
      this.car = car;   
   }         
}

boss的Bean可通过<ref>元素引用car Bean, 建立起boss对car的依赖.

<!--car Bean -->
<bean id="car" class="com.attr.Car"/>
<bean id="boss" class="com.attr.Boss">
       <-- 引用car Bean -->
       <property name="car" ref="car"/>
</bean>

<ref>元素可以通过以下三个属性引用容器中其他Bean:

(1) bean: 通过该属性,可以应用同一容器或者父容器中定义的其他bean

(2) local: 通过该属性, 只能引用同一配置文件中定义的其他bean, 它可以利用Xml解析器自动检验引用的合法性.`  

(3) parent: 只能引用父容器中的bean, 如<ref parent="car">的配置说明car的Bean是父容器中的bean

  

  如果car Bean只被boss Bean引用而不会被容器中任何其他的Bean引用, 则可以将car以内部Bean的方式注入到Boss中:

<bean id="boss" class="com.attr.Boss">
        <property name="car">
            <bean class="com.attr.Car">
                <property name="brand" value="奥迪"/>
                <property name="maxSpeed" value="300"/>
            </bean>
        </property>
    </bean>

 内部bean及时提供了id, name, scope属性, 也会被忽略, scope默认为prototype类型

Spring学习笔记四

标签:

原文地址:http://www.cnblogs.com/NewMan13/p/5227605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!