Spring Autowiring byName with Example

In Spring "AutoWiring byName" means Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire byname, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property. We can Enable This Feature by Adding "autowire = "byName" to The beans Tag in Spring Configuration File(i.e.applicationContext.xml).

So Friends with out wasting We will See Example

Tools Used In This Article

  • Spring 4.3.2
  • Maven 4.0.0
  • JDK 1.7

Project Directory Structure

Please See The Complete Project Directory Structure below

Maven Dependencies

add spring-core,spring-beans and spring-context related maven dependencies to the pom.xml File


<project xmlns="http://maven.apache.org/POM/4.0.0"




Writing Spring Beans


package com.practice;

public class Account {
private int accountId;
private String name;
private Aadhar aadhaar;
public int getAccountId() {
return accountId;
public void setAccountId(int accountId) {
this.accountId = accountId;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public Aadhar getAadhaar() {
return aadhaar;
public void setAadhaar(Aadhar aadhaar) {
this.aadhaar = aadhaar;
public String toString() {
return "Account [accountId=" + accountId + ", name=" + name
+ ", aadhaar=" + aadhaar + "]";



package com.practice;

public class Aadhar {
private int aadhaarNumber;

public int getAadhaarNumber() {
return aadhaarNumber;

public void setAadhaarNumber(int aadhaarNumber) {
this.aadhaarNumber = aadhaarNumber;

public String toString() {
return "Aadhar [aadhaarNumber=" + aadhaarNumber + "]";


Setting up The Spring Configuration File

In Spring We need to Enable autowire=byName like below.


<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
<bean id = "accountBean" class = "com.practice.Account" autowire = "byName">
<property name = "accountId" value = "11111"></property>
<property name="name" value = "xxxxx">&l/property>
<bean id = "aadhaar" class = "com.practice.Aadhar">
<property name = "aadhaarNumber" value = "2222"></property>

Let,s create Test class and Run The code

package com.practice.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.practice.Account;

public class AppTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Account account = (Account)context.getBean("accountBean");




Account [accountId=11111, name=xxxxx, aadhaar=Aadhar [aadhaarNumber=2222]]