spring - constructor-arg conventional usage

 1, when using the constructor injection, using constructor-arg sub-tab to specify constructor arguments.   

<bean id="provider" class="com.apress.prospring.ch4.ConfigurableMessageProvider">   

    <constructor-arg>   

        <value>This is a configurable message</value>   

    </constructor-arg>   

</bean>   

 

2, when a plurality of parameters constructors, use the index property constructor-arg tag, attribute values ​​from the index zero.   

<bean id="provider" class="com.apress.prospring.ch4.ConfigurableMessageProvider">   

    <constructor-arg index="0">   

        <value>first parameter</value>   

    </constructor-arg>   

    <constructor-arg index="1">   

        <value>second parameter</value>   

    </constructor-arg>   

</bean>   

 

3, when using constructor injection, you need to pay attention to the problem is to avoid the occurrence of conflicts constructor. Consider the following scenario:   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public  class  ConstructorConfusion {  
 
public  ConstructorConfusion(String someValue) {  
 
         System.out.println( "ConstructorConfusion(String) called" );  
 
     }  
 
public  ConstructorConfusion( int  someValue) {  
 
         System.out.println( "ConstructorConfusion(int) called" );  
 
     }  
 
}  

 Use the following configuration file   

<bean id="constructorConfusion" class="com.apress.prospring.ch4.ConstructorConfusion">   

    <constructor-arg>   

        <value>90</value>   

    </constructor-arg>   

</bean>   

  Then, when an instance of the component constructorConfusion when the output ConstructorConfusion (String) called, that is to say parameters of type String constructor is called, which obviously does not meet our requirements. In order to allow Spring to call parameters int constructor to instantiate components constructorConfusion, we need to explicitly tell Spring in the configuration file, which requires the use of a constructor, which requires the use of the type attribute constructor- arg.   

<bean id="constructorConfusion" class="com.apress.prospring.ch4.ConstructorConfusion">   

    <constructor-arg type="int">   

        <value>90</value>   

    </constructor-arg>   

</bean>  

 

Guess you like

Origin www.cnblogs.com/Jeely/p/11113856.html