Java Techies- Solution for All
Spring Constructor Injection Example
Student.java File
package com.jtechies; public class Student { private String name; private Course course; private String rollNo; public Student(String name, Course course, String rollNo){ this.name=name; this.course=course; this.rollNo=rollNo; } public String toString(){ return "name = "+name+"\n" +course+"\nroll no = "+rollNo; } }
Course.java File
package com.jtechies; public class Course { private String name; private String duration; public Course(String name, String duration){ this.name=name; this.duration=duration; } public String toString(){ return "course name = "+name+ "\ncourse duration = "+duration; } }
Test.java File
package com.jtechies; import org.springframework.context.ApplicationContext; import org.springframework.context.support. ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Student student= (Student)context.getBean("student"); System.out.println(student); } }
Beans.xml file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans /spring-beans-3.0.xsd"> <bean id="student" class="com.jtechies.Student"> <constructor-arg value="peter" /> <constructor-arg ref="course" /> <constructor-arg value="1001" /> </bean> <bean id="course" class="com.jtechies.Course"> <constructor-arg value="B.tech" /> <constructor-arg value="4 years" /> </bean> </beans>
Output
name = peter course name = B.tech course duration = 4 years roll no = 1001