Spring 核心技术IoC容器 (三)

本文将继续前文,针对依赖注入的细节进行描述

依赖注入细节

如前文所述,开发者可以通过定义Bean的依赖的来引用其他的Bean或者是一些值。Spring基于XML的配置元数据支持一些子元素<property/>以及<constructor-arg/>来达到这一目的。

内在值类型(Java Primitives类型,字符串等)

元素<property/>value属性来以易读的形式配置一个属性或者构造参数。Spring的遍历就是用来讲这些字符串的值转换成指定的类型。

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <!-- results in a setDriverClassName(String) call -->
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
    <property name="username" value="root"/>
    <property name="password" value="masterkaoli"/>
</bean>

下面的例子使用的p命名空间,更为简单的XML配置。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/mydb"
        p:username="root"
        p:password="masterkaoli"/>

</beans>

上面的XML更为的简洁,但是,属性的类型是在运行时确定的,而非设计时的,除非使用IntelliJ IDEA或者Spring Tool Suite这些工具才能在定义Bean的时候自动完成属性配置。当然很推荐使用这些IDE。

开发者也可以定义一个java.util.Properties实例,比如:

<bean id="mappings"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <!-- typed as a java.util.Properties -->
    <property name="properties">
        <value>
            jdbc.driver.className=com.mysql.jdbc.Driver
            jdbc.url=jdbc:mysql://localhost:3306/mydb
        </value>
    </property>
</bean>

Spring的容器会将<value/>里面的文本通过使用JavaBean的PropertyEditor机制转换成一个java.util.Properties实例。这也是一个捷径,也是一些Spring团队更喜欢使用嵌套的<value/>元素而不是value属性风格。

idref元素

idref元素是一种简单的提前校验错误的方式,通过id来关联容器中的其他的Bean的方式。

<bean id="theTargetBean" class="..."/>

<bean id="theClientBean" class="...">
    <property name="targetName">
        <idref bean="theTargetBean" />
    </property>
</bean>

上述的Bean的定义在运行时,和如下定义是完全一致的。

<bean id="theTargetBean" class="..." />

<bean id="client" class="...">
    <property name="targetName" value="theTargetBean" />
</bean>

第一种方式是更值得提倡的,因为使用了idref标签,会是的容器在部署阶段就针对Bean进行校验,确保Bean一定存在。而第二个版本的话,是没有任何校验的。只有实际上引用了Bean client,实例化client的时候才会发现。如果client是一个prototype的Bean,那么类似拼写之类的错误会在容器部署以后很久才能发现。

idref元素的local属性在4.0以后的xsd中已经不再支持了,而是使用了bean引用。如果更新版本,需要将idref local引用都转换成 idref bean即可。

引用其他的Bean

ref元素在<constructor-arg/>或者<property/>中的一个终极标签。开发者通过这个标签配置Bean引用另一个Bean。当需要引用一个Bean的时候,该Bean会先实例化,然后配置属性,也就是引用的依赖。如果该Bean是单例Bean的话,那么该Bean会早由容器初始化。最终的引用另一个对象的所有引用。Bean的范围以及校验取决于开发者是否通过bean,local,parent这些属性来指定对象的id或者name属性。

通过指定Bean的bean属性的<ref/>来指定依赖是最常见的方式,可以容器或者父容器中的Bean,无论引用是否在同一个XML文件。其中bean属性中的值可以和其他引用Bean中的id属性一致,或者和其中的一个name属性一致。

<ref bean="someBean"/>

通过指定Bean的parent属性会创建一个引用到当前容器的父容器之中。

<!-- in the parent context -->
<bean id="accountService" class="com.foo.SimpleAccountService">
    <!-- insert dependencies as required as here -->
</bean>
<!-- in the child (descendant) context -->
<bean id="accountService" <!-- bean name is the same as the parent bean -->
    class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
        <ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
    </property>
    <!-- insert other configuration and dependencies as required here -->
</bean>

开发者使用当Bean存在多层次的容器中需要包裹到大理之中,可以按照如下进行配置。

idref标签一样,ref元素中的local标签在xsd 4.0以后已经不再支持了,开发者可以通过将已存在的ref local改为ref bean来完成更新Spring。

内部Bean

定义在<bean/>元素的<property/>或者<constructor-arg/>元素之内的Bean叫做内部Bean

<bean id="outer" class="...">
    <!-- instead of using a reference to a target bean, simply define the target bean inline -->
    <property name="target">
        <bean class="com.example.Person"> <!-- this is the inner bean -->
            <property name="name" value="Fiona Apple"/>
            <property name="age" value="25"/>
        </bean>
    </property>
</bean>

内部Bean的定义是不需要指定id或者名字的。如果指定了,容器也不会使用之作为分别Bean的区分标识。容器同时也会无视内部Bean的scope标签:内部Bean 总是 匿名的,而且 总是 随着外部的Bean同时创建的。开发者是无法将内部的Bean注入到外部Bean以外的其他Bean的。

当然,也有可能从自定范围接收到破坏性回调。比如:一个请求范围的内部Bean包含了一个单例的Bean,那么内部Bean实例会绑定到包含的Bean,而包含的Bean允许访问到request的scope生命周期。这种场景不常见,内部Bean通常只是共享它的外部Bean。

集合

<list/>,<set/>,<map/><props/>元素中,开发者可以配置Java集合类型List,Set,Map以及Properties的属性和参数。

<bean id="moreComplexObject" class="example.ComplexObject">
    <!-- results in a setAdminEmails(java.util.Properties) call -->
    <property name="adminEmails">
        <props>
            <prop key="administrator">[email protected]</prop>
            <prop key="support">[email protected]</prop>
            <prop key="development">[email protected]</prop>
        </props>
    </property>
    <!-- results in a setSomeList(java.util.List) call -->
    <property name="someList">
        <list>
            <value>a list element followed by a reference</value>
            <ref bean="myDataSource" />
        </list>
    </property>
    <!-- results in a setSomeMap(java.util.Map) call -->
    <property name="someMap">
        <map>
            <entry key="an entry" value="just some string"/>
            <entry key ="a ref" value-ref="myDataSource"/>
        </map>
    </property>
    <!-- results in a setSomeSet(java.util.Set) call -->
    <property name="someSet">
        <set>
            <value>just some string</value>
            <ref bean="myDataSource" />
        </set>
    </property>
</bean>

当然,map的key或者value,或者是集合的value都可以配置为下列之中的一些元素:

bean | ref | idref | list | set | map | props | value | null

集合合并

Spring的容器也支持来合并集合。开发者可以定义一个父样式的<list/>,<map/>,<set/>或者<props/>,同时有子样式的<list/>,<map/>,<set/>或者<props/>继承并且覆盖父集合。也就是说,子集合的值是父元素和子元素集合的合并值。比如下面的例子。

<beans>
    <bean id="parent" abstract="true" class="example.ComplexObject">
        <property name="adminEmails">
            <props>
                <prop key="administrator">[email protected]</prop>
                <prop key="support">[email protected]</prop>
            </props>
        </property>
    </bean>
    <bean id="child" parent="parent">
        <property name="adminEmails">
            <!-- the merge is specified on the child collection definition -->
            <props merge="true">
                <prop key="sales">[email protected]</prop>
                <prop key="support">[email protected]</prop>
            </props>
        </property>
    </bean>
<beans>

可以发现我们在childBean上使用了merge=true属性。当childBean由容器初始化,实例化的时候,其实例中包含的adminEmails集合就是childadminEmails以及parentadminEmails集合。如下:

[email protected].com
[email protected].com
[email protected].co.uk

childProperties集合的值继承了parent<props/>child的值也支持重写parent的值。

这个合并的行为和<list/>,<map/>以及<set/>之类的集合类型的行为是类似的。<list/>的特定的例子中,与List集合类型类似,有隐含的ordered概念的。所有的父元素里面的值,是在所有孩子元素的值之前的。但是像Map,Set或者Properties的集合类型,是不存在顺序的。

集合合并的限制

开发者是不能够合并不同类型的集合的(比如MapList合并),如果开发者这么做,会抛出异常。merge的属性是必须特指到更低级或者继承者,子节点的定义上。特指merge属性到腹肌和定义上是冗余的,而且在合并上也没有任何效果。

强类型集合

在Java 5以后,开发者可以使用强类型的集合了。也就是,开发者可以声明一个Collection类型,然后这个集合只包含String元素(举例来说)。如果开发者通过Spring来注入强类型的Collection到Bean中,开发者就可以利用Spring的类型转换支持来做到。

public class Foo {

    private Map<String, Float> accounts;

    public void setAccounts(Map<String, Float> accounts) {
        this.accounts = accounts;
    }
}
<beans>
    <bean id="foo" class="x.y.Foo">
        <property name="accounts">
            <map>
                <entry key="one" value="9.99"/>
                <entry key="two" value="2.75"/>
                <entry key="six" value="3.99"/>
            </map>
        </property>
    </bean>
</beans>

foo的属性accounts准备注入的时候,accounts的泛型信息Map<String, Float>就会通过反射拿到。这样,Spring 的类型转换系统能够识别不同的类型,如上面的例子Float然后将字符串的值9.99, 2.75以及3.99转换成对应的Float类型。

Null以及空字符串

Spring将会将属性的空参数,直接当成空字符串来处理。下面的基于XML的元数据配置就会将email属性配置为String的值为""

<bean class="ExampleBean">
    <property name="email" value=""/>
</bean>

上面的例子和下列JAVA代码是一致的。

exampleBean.setEmail("")

<null/>元素来处理null的值。如下:

<bean class="ExampleBean">
    <property name="email">
        <null/>
    </property>
</bean>

上面的代码和下面的Java代码是一样的效果:

exampleBean.setEmail(null)

XML 快捷方式p命名空间

p命名空间令开发者可以使用bean的属性,而不用使用嵌套的<property/>元素,就能描述开发者想要注入的依赖。

Spring是支持基于XML的格式化的命名空间扩展的。本节讨论的beans的配置都是基于XML的,p命名空间不是定义在XSD文件,而是在Spring的核心之中的。

下面展示了两种XML片段是同样的解析结果:第一个使用的标准的XML格式,而第二种使用了p命名空间。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="classic" class="com.example.ExampleBean">
        <property name="email" value="[email protected]"/>
    </bean>

    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="[email protected]"/>
</beans>

上面的例子在Bean中展示了email属性的定义。这种定义告知Spring这是一个属性的声明。如前面所描述,p命名空间并没有标准模式定义,所以你可以配置属性的名字为依赖名字。

下面的例子包括了2个Bean定义,引用了另外的Bean:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="john-classic" class="com.example.Person">
        <property name="name" value="John Doe"/>
        <property name="spouse" ref="jane"/>
    </bean>

    <bean name="john-modern"
        class="com.example.Person"
        p:name="John Doe"
        p:spouse-ref="jane"/>

    <bean name="jane" class="com.example.Person">
        <property name="name" value="Jane Doe"/>
    </bean>
</beans>

从上述的例子中可以看出,john-modern不止包含一个属性,也同时使用了特殊的格式来声明一个引用指向另一个Bean。第一个Bean定义使用的是<property name="spouse" ref="jane"/>来创建的Bean引用到另外一个Bean,而第二个Bean的定义使用了p:spouse-ref="jane"来作为一个指向Bean的引用。在这个例子中spouse是属性的名字,而-ref部分表名这个依赖不是直接的类型,而是引用另一个Bean。

p命名空间并不同标准的XML格式一样灵活。比如,声明属性的引用可能和一些以Ref结尾的属性相冲突,而标准的XML格式就不会。Spring团队推荐开发者能够和团队商量一下,要使用哪一种方式,而不要同时使用3中方法。

XML 快捷方式c命名空间

与p命名空间类似,c命名空间是在Spring 3.1首次引入,c命名空间允许内联的属性来配置构造参数而不用使用constructor-arg元素。

下面就是一个使用了c命名空间的例子:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="bar" class="x.y.Bar"/>
    <bean id="baz" class="x.y.Baz"/>

    <!-- traditional declaration -->
    <bean id="foo" class="x.y.Foo">
        <constructor-arg ref="bar"/>
        <constructor-arg ref="baz"/>
        <constructor-arg value="[email protected]"/>
    </bean>

    <!-- c-namespace declaration -->
    <bean id="foo" class="x.y.Foo" c:bar-ref="bar" c:baz-ref="baz" c:email="[email protected]"/>

</beans>

c:命名空间使用了和p:命名空间想问类似的方式(使用了-ref来配置引用)。而且,同样的,c命名空间不是定义在XSD的模式之中(但是在Spring核心之中)。

在少数的例子之中,构造函数的参数名字并不可用(通常,如果字节码没有debug信息的编译),开发者可以使用下面的例子:

<!-- c-namespace index declaration -->
<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz"/>

根据XML语法,索引的概念的存在要求使用_作为XML属性名字不能以数字开始。

实际上,构造函数的解析机制在匹配参数是很高效的,除非必要,Spring团队推荐在配置中使用命名空间。

混合的属性

开发者可以在配置属性的时候配置混合的属性,只要所有的组件路径(除了最后一个属性名字)不能为null

参考如下的定义。

<bean id="foo" class="foo.Bar">
    <property name="fred.bob.sammy" value="123" />
</bean>

foo有一个fred的属性,而其中fred属性有一个bob属性,而bob属性之中有一个sammy属性,那么最后这个sammy属性会配置为123。想要上述的配置能够生效,fred属性需要有一个bob属性且在fred构造只是构造之后不为null,否则会抛出NullPointerException

时间: 2024-08-28 14:15:36

Spring 核心技术IoC容器 (三)的相关文章

Spring核心技术IoC容器(五)

前文概述了Spring的容器,Bean,以及依赖的一些信息,本文将描述一下Bean的作用域 Bean的作用域 当开发者定义Bean的时候,同时也会定义了具体如何创建Bean实例的步骤.这些步骤是很重要的,因为只有通过这些配置,开发者才能创建实例对象. 开发者不仅可以控制多种多样的依赖到Bean之中,也可以配置Bean的作用域.这种方法是非常强大而且弹性也非常好,开发者可以通过配置来指定对象的作用域,而不用在Java类层次上来配置.Bean可以配置多种作用域.Spring框架支持5中作用域,有三种

Spring核心技术IoC容器(八)

本文针对自动装载的一些注解进行描述. 基于注解的容器配置 @Required注解 @Required注解需要应用到Bean的属性的setter方法上面,如下面的例子: public class SimpleMovieLister { private MovieFinder movieFinder; @Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } //

Spring核心技术IoC容器(六)

前文已经描述了Bean的作用域,本文将描述Bean的一些生命周期作用,配置还有Bean的继承. 定制Bean 生命周期回调 开发者通过实现Spring的InitializeingBean和DisposableBean接口,就可以让容器来管理Bean的生命周期.容器会调用afterPropertiesSet()前和destroy()后才会允许Bean在初始化和销毁Bean的时候执行一些操作. JSR-250的@PostConstruct和@PreDestroy注解就是现代Spring应用生命周期回

Spring 核心技术 IoC容器(一)

IoC 容器 IoC容器和Bean简介 这章包括了Spring框架对于IoC规则的实现.Ioc也同DI(依赖注入).而对象是通过构造函数,工厂方法,或者一些Set方法来定义对象之间的依赖的.容器在创建这些Bean对象的时候同时就会注入这些依赖.这个过程是根本上的反转了,不再由Bean本身来控制实例化和定位依赖,而是通过服务定位来控制这个过程,也是IoC(控制反转)的由来. org.springframework.beans和org.springframework.context包是Spring框

Spring核心技术IoC容器(七)

本文将讨论如何关于在Spring生命周期中扩展Spring中的Bean功能. 容器的扩展 通常来说,开发者不需要通过继承ApplicationContext来实现自己的子类扩展功能.但是Spring IoC容器确实可以通过实现接口来增加一些功能.下面将描述一下这些接口. 通过BeanPostProcessor定义Bean BeanPostProcessor接口定义了一些回调方法,开发者可以通过实现来自己的实例化逻辑,依赖解析逻辑等等.如果开发者只是想在Spring容器完成了实例化,配置以及初始化

Spring核心技术IoC容器(四)

前面两篇文章描述了IoC容器中依赖的概念,包括依赖注入以及注入细节配置.本文将继续描述玩全部的依赖信息. 使用 depends-on 如果一个Bean是另一个Bean的依赖的话,通常来说这个Bean也就是另一个Bean的属性之一.多数情况下,开发者可以在配置XML元数据的时候使用<ref/>标签.然而,有时Bean之间的依赖关系不是直接关联的.比如:需要调用类的静态实例化器来出发,类似数据库驱动注册.depends-on属性会使明确的强迫依赖的Bean在引用之前就会初始化.下面的例子使用dep

Spring 核心技术IoC容器(二)

本文将继续前文,描述Spring IoC中的依赖处理. 依赖 一般的企业应用也不会只有一个对象(或者是Spring Bean).甚至最简单的应用都要有一些对象来协同工作来让终端用户看到一个完整的应用.下一部分将解释开发者从单独的定义Bean,到让这些对象在一个应用中协同工作. 依赖注入 依赖注入是一个让对象只通过构造参数,工厂方法的参数或者配置的属性来定义他们的依赖.这些依赖也是对象所需要协同工作的对象.容器在之后会在创建Bean的时候注入这些依赖.整个过程完全反转了Bean自己控制实例化或者,

Spring的IOC容器—依赖注入

前面一篇博客大致讲了一下Spring的IOC容器的原理,IOC即控制反转主要是依靠依赖注入的方式来实现的.依赖注入是指所依赖的对象不是由自己new出来的,而是用别的方式像打针似的注入进来. 其实说白了不管是控制反转还是依赖注入都说明了Spring采用动态.灵活的方式来管理各种对象. Spring的依赖注入对调用者和被调用者几乎没有任何要求,完全支持对POJO之间依赖关系的管理.有以下几种注入方式: 1. Setter 注入 因为对于javaBean来说,我们可以通过setter和getter方法

好莱坞原则—Spring的IOC容器

IOC容器的概念,之前在学习SSH的时候,就有接触过.但那时候也仅仅是知道这么个概念,认为它非常难理解.事实上并非它难理解,而是我并没有停下来好好对它总结梳理过. IOC(Inversion of Control)简单介绍: 控制反转",并非一种技术.而是一种思想.一种主动提供服务的思想.所谓IOC,就是由Spring负责控制对象的生命周期和对象间的关系,与我们传统的在对象内部直接控制背道而驰. 在传统的程序开发中,完毕一个业务逻辑至少须要两个或两个以上的对象协助完毕.通常一个对象要使用另外一个