Ranju Pillai
Ranju Pillai

Reputation: 51

Exception with Autowired

In autowiring byType if the property type is matched with more than one bean then it would throw an exception, but I can't see any exception when I am using the annotation @Autowired and defined two beans with same property type. Below is the code: Employee.java:

public class Employee {
    private int id;
    private String name;
    private int salary;

    // Getter and Setter
}

Dept:

public class Dept {
    @Autowired
    private Employee emp;

    public Employee getEmp() {
        return emp;
    }
    public void setEmp(Employee emp) {
        this.emp = emp;
    }
    @Override
    public String toString() {
        return emp.getName();
    }
}

Beans.xml:

<bean id = "dept" class = "Dept"></bean>

    <bean id = "emp" class = "Employee">
    <property name="id" value="25"></property>
    <property name="name" value="Ram"></property>
    <property name="salary" value="32000"></property>
    </bean>

    <bean id = "emp1" class = "Employee">
    <property name="id" value="25"></property>
    <property name="name" value="Sanju"></property>
    <property name="salary" value="32000"></property>
</bean>

AppMain.java:

public class AppMain {

        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
            Dept d = (Dept)context.getBean("dept");
            System.out.println(d);
        }
    }

Please correct me if I am doing any thing wrong in it.

Upvotes: 1

Views: 494

Answers (2)

saurabh kumar
saurabh kumar

Reputation: 164

You have defined a variable named as "emp" of Employee class which is same as the bean with id as "emp".Because of this spring don't get confused understanding which bean it has to inject.and if you change the bean id from "emp" to something else you will get an unsatisfied bean dependency exception. read more here

Upvotes: 0

Gary Russell
Gary Russell

Reputation: 174554

Spring is matching the emp variable name; if your beans were emp1 and emp2 you'd get an exception (unless you add a @Qualifier to the @AutoWired field).

Upvotes: 4

Related Questions