Spring XML设置bean的构造参数和属性方法

XML设置bean的构造参数和属性方法

构造参数

  • 最简单的,不用指定contructor parameter的index和type
    Bean:

    package x.y;
    
    public class Foo {
    
    public Foo(Bar bar, Baz baz) {
        // ...
    }
    }

    XML:

    <beans>
    <bean name="foo" class="x.y.Foo">
        <constructor-arg>
            <bean class="x.y.Bar"/>
        constructor-arg>
        <constructor-arg>
            <bean class="x.y.Baz"/>
        constructor-arg>
    bean>
    beans>

    这种适合Contructor的参数type不相同,并且bean没有继承的关系。默认的匹配方法是by type.如果是简单类型的话就不行了,因为xx这样的形式,spring不能知道是具体的哪种类型,可能是int也可能是String.参照下面的例子.

  • Constructor Argument Type Matching
    Bean:

    package examples;
    
    public class ExampleBean {
    
     // No. of years to the calculate the Ultimate Answer
     private int years;
    
     // The Answer to Life, the Universe, and Everything
     private String ultimateAnswer;
    
     public ExampleBean(int years, String ultimateAnswer) {
         this.years = years;
         this.ultimateAnswer = ultimateAnswer;
     }
    } 

    XML:

    "exampleBean" class="examples.ExampleBean">
    type="int" value="7500000"/>
    type="java.lang.String" value="42"/>
    
  • Constructor Argument Index
    还是使用上面的bean






Constructor和Properties的写法:

  • Properties的bean ref写法有两种:
    • 单独使用ref:



    • 使用内嵌的ref:


  • Constructor的bean ref写法有两种:
    • 单独使用ref:





    • 使用内嵌的ref:



其他的设置(包括property和contructor)

  • Straight values (primitives, Strings, etc.)
    • 方式一:


      com.mysql.jdbc.Driver

    • 方式二:


  • Collections
    • List



      a list element followed by a reference



    • Map





      an entry

      just some string



      a ref





    • Set



      just some string




另外值得一提的还有一种写法:

The p-namespace(从Spring2.0之后开始)

使用这种需要包括一个schemahttp://www.springframework.org/schema/p但是这个特殊的schema不需要schemaLocation,所以可以设置为任何的字段.

直接看一个例子:

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


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

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

根据官方备注,这种写法需要仔细考虑,因为像例子中提到的spouse-ref实际是一个spouse字段,如果实际bean中包括一个spouse字段就会产生冲突,而且不容易阅读。所以需要仔细考虑这么写的必要性.

你可能感兴趣的:(Hibernate,Spring)