Search code examples
javaspringjavabeans

How to assign a class property passing value to class constructor using Dependency injection in spring?


I am kind of super new to spring. I need to assign a value to my class property using the constructor. I am using the class constructor method in spring dependency injection to do that. How to configure bean XML to do that.


Solution

  • MyBean1.class:

      public class MyBean1{
          private MyBean2 bean2;
          public MyBean1(MyBean2 bean2){
             this.bean2=bean2;
          }
      }
    

    XML:

      <!-- Definition for bean1 -->
       <bean id = "bean1" class = "com.MyBean1">
          <constructor-arg ref = "bean2"/>
       </bean>
    
       <!-- Definition for bean2 -->
       <bean id = "bean2" class = "com.MyBean2"></bean>