Autowiring in Spring Example – Autowire byType

Autowire byName
If the name or id of the bean declared in applicationContext.xml (or xml which you create) is same as the name of the bean property then autowire byName can be applied

Autowire byType
Means it will search for one bean of given property in the container(Only one bean). If there are more than one bean, then it will not autowire.

Autowire Constructor
It will search for compatible constructor with given parameters

Autowire byName

Directory Structure

package com.javainfinite;

public class employee {
    private String ename;
    private int id;

    public String getEname() {
        return ename;

    public void setEname(String ename) {
        this.ename = ename;

    public int getId() {
        return id;

    public void setId(int id) { = id;

package com.javainfinite;

public class employeedependent {
    employee employee1;
    employee employee2;

    public employee getEmployee1() {
        return employee1;

    public void setEmployee1(employee employee1) {
        this.employee1 = employee1;

    public employee getEmployee2() {
        return employee2;

    public void setEmployee2(employee employee2) {
        this.employee2 = employee2;

    public void display()
        System.out.println("Employee Name: "+employee1.getEname()+" ID: "+employee1.getId());
        System.out.println("Employee Name: "+employee2.getEname()+" ID: "+employee2.getId());

package com.javainfinite;

import org.springframework.context.ApplicationContext;

public class operational {
    public static void main(String args[])
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        employeedependent emp=(employeedependent) ac.getBean("employeedependent");


<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns=""

<bean id="employeedependent" class="com.javainfinite.employeedependent" autowire="byType">

<bean id="employee1" class="com.javainfinite.employee">
            <property name="ename" value="Alpha"/>
            <property name="id" value="001"/>


Note: autowire byType applies for exactly one type, here we have declared only one type of bean and it has applied to that. In output you can see, the value for employee2.getEname() also shows the same value of employee1.getEname(). This is cause the byType applies depending on the type








By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *