7.4.2 XML shortcut with the c-namespace

Similar to the the section called “XML shortcut with the p-namespace”, the c-namespace, newly introduced in Spring 3.1, allows usage of inlined attributes for configuring the constructor arguments rather then nested constructor-arg elements.

XML shortcut with the p-namespace这一章节相似,c名称空间在Spring 3.1的时候被引进,允许给配置构造器参数使用内联属性而不是嵌套的 constructor-arg 元素.

Let’s review the examples from the section called “Constructor-based dependency injection” with the c: namespace:

让我们来评审一下来自Constructor-based dependency injection这一章节通过使用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>

The c: namespace uses the same conventions as the p: one (trailing -ref for bean references) for setting the constructor arguments by their names. And just as well, it needs to be declared even though it is not defined in an XSD schema (but it exists inside the Spring core).

c名称空间使用了和p名称空间相同的转换(尾部跟着 -ref 作为bean引用),通过它们的名字去设置构造器参数.c名称空间他需要被声明,甚至它不是被定义在XSD约束中(但它存在于Spring核心中).

For the rare cases where the constructor argument names are not available (usually if the bytecode was compiled without debugging information), one can use fallback to the argument indexes:

一种罕见的情况是没有构造器参数名称(通过是如果字节码被编译时没有反编译信息的话),一种可用的方法是通过参数索引:

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

Due to the XML grammar, the index notation requires the presence of the leading _ as XML attribute names cannot start with a number (even though some IDE allow it).

由于XML语法,索引符号作为属性名称,它的开头必须存在_,它不能够以数字开头(尽管有点IDE允许).

In practice, the constructor resolution mechanism is quite efficient in matching arguments so unless one really needs to, we recommend using the name notation through-out your configuration.

扫描二维码关注公众号,回复: 2544465 查看本文章

实际上,构造器解析机制在匹配参数时十分有效率,如果你真的需要的话,我们建议在你的配置中至始至终都使用名称符号.

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80883442