9.Constructor Injection – Primitive data Injection

Constructor Injection – Primitive data Injection
·         we don’t have name attribute, we have to pass type – value – index if needed
·         you must pass Constructor arg, if our Bean contains parameterized  constructor
·         If not pass arg const. it won’t create even def. Constructor
·         we won’t pass same type of Constructor with same data
·         If u have overloading Constructor (same no args –differ type) u can solve by using Type attribute
·         we can pass more than one value using this, but it's not possible in setter
·         It any ambiguity in data type it will solve by order of Constructor
·         Constructor with more no.of params we will use INDEX attribute.
·         Overriding of index value can possible by const injection
Syntax
<constructor-arg index="" type="" value="" ref=""/>
                  Index à parameter position
                  Type à String, int, float
                  Value à value to be inject
                  Ref à if any reference





Example:
StudentBean.java
package bean;

public class StudentBean {
     private int sno;
     private String name;
     public StudentBean(){
            System.out.println("Def. const");
     }
           
     public StudentBean(int sno, String name)
     {
            System.out.println("Param. const");
            this.sno = sno;
            this.name = name;
     }
    
     public void getData(){
            System.out.println(sno+": "+name);
     }

}

MainClass.java
package main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import bean.StudentBean;

public class MainClass {
       public static void main(String[] args) {
              BeanFactory factory = new ClassPathXmlApplicationContext("res/s.xml");
              StudentBean bean = (StudentBean) factory.getBean("ob");
              bean.getData();
       }

}


res/s.xml

<beans>    
     <bean id="ob" class="bean.StudentBean">
            <constructor-arg index="0" value="100"/>
            <constructor-arg index="1" type="java.lang.String" value="Satya"/>
     </bean>
</beans>


Output
-    - - - - - - - - - - - - - -
-    Param. const
-    100: Satya

Post a Comment

Thank You

Previous Post Next Post