Hi I am new to spring technology. I have a class called Employee as follows which has 2 constructors with different argument types. I am able to inject values to one of the constructors as described in the xml file. May I know how to inject value to other constructor as well using constructor injection. I tried various possibilities but unable to figure out how to do it.
public class Employee { private int eno ; private String name ; private double salary ; private String desig ; public Employee(int eno, String name) { this.eno = eno; this.name = name; } public Employee(double salary, String desig) { this.salary = salary; this.desig = desig; } public void showInjectedValues() { System.out.println("Eno : " + eno); System.out.println("name : " + name); System.out.println("salary : " + salary); System.out.println("desig : " + desig); } } Trying to inject with spring.xml and the Java class for Injection is as follows:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InjectionTest { static ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springconfig.xml"); public static void main(String[] args) { Employee employee = (Employee) applicationContext.getBean("employee"); employee.showInjectedValues(); } } applicationContext.xml is as follows:
<?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.2.xsd"> <bean id="employee" class="com.vidvaan.spring.Employee"> <constructor-arg value="2000" index="0" type="double" /> <constructor-arg value="team lead" index="1" type="java.lang.String" /> </bean> </beans>