יום שני, 13 במאי 2013

spring ref parent

The following sample demonstrate the use of spring ref parent.
The Sample contain two Spring XML configuration files that are declared as followed :

The parent configuration file :

<beans>
.
<bean id="accountService" class="javaapplicationbasicspring.SimpleAccountService">
        <property name="Value">
            <value>Hello Zvika</value>
        </property>
    </bean>
</beans>

The child configuration file
<beans>
  < bean id="accountService" class="javaapplicationbasicspring.SimpleAccountService">
        <property name="Parent">
           <ref parent="accountService"/>
        </property>
    </bean>
</beans>

Please note that the child assign the value of the Parent property based on the value from the parent xml configuration file .
The beans ids in the parent and child  are the some in this example but it isn't mandatory .

The Bean declaration :

  1: public class SimpleAccountService {
  2:   
  3:    private String mString;
  4:    private SimpleAccountService mParent;   
  5: 
  6:     public SimpleAccountService getParent() {
  7:         return mParent;
  8:     }
  9: 
 10:     public void setParent(SimpleAccountService mParent) {
 11:         this.mParent = mParent;
 12:     }
 13:    
 14:     public SimpleAccountService()
 15:     {
 16:     }
 17:     
 18:     public String getValue ()
 19:     {
 20:         return mString;
 21:     }
 22:  
 23:     public void setValue (String pValue )
 24:     {
 25:          mString = pValue; 
 26:     }
 27:     
 28:     public void DoTest()
 29:     {
 30:         System.out.print ("Hello: " + mParent.getValue());
 31:     }
 32: }

 The main / test program :
  1: public class JavaApplicationBasicSpring 
  2: {  
  3:     public static void main(String[] args)
  4:     {  
  5:     ClassPathXmlApplicationContext appContextParent = new ClassPathXmlApplicationContext(   new String[] {"resources/ParentSpringXMLConfig.xml"
  6:     ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( new String[] {"resources/SpringXMLConfig.xml"} ,appContextParent )
  7:     SimpleAccountService theSimpleAccountService =  (SimpleAccountService)appContext.getBean("accountService"); 
  8:     theSimpleAccountService.DoTest(); 
  9:   } 
 10: }
please note:
In line 11 setting the parent of the child context
The relative path of  resources/ParentSpringXMLConfig.xml in order to void the file not found exception .

The package and imports
package javaapplicationbasicspring;
import org.springframework.context.support.ClassPathXmlApplicationContext
The files structure is as follow :


Capture2


 


אין תגובות:

הוסף רשומת תגובה