Spring Autowiring

Autowiring byName

Autowiring a bean byName simply checks the property of the mapped class and then reads the configuration metadata (i.e configuration xml or java based configuration) to find the bean with matching name. If found then that bean is automatically wired. This is why it is known as autowiring byName as it works for matching name between java pojo and configuration file.


Explained below is an example of autowiring bean byName.


Java POJO - WriteMessage.java

package com.autowirepkg;

public class WriteMessage {

	private String message;
	private String sender;
	private String reciever;
	public WriteMessage(String message,String sender,String reciever ){
		this.message = message;
		this.sender = sender;
		this.reciever = reciever;
	public void messageDetails(){
		System.out.println("Message: "+ message);
		System.out.println("Sender: "+ sender);
		System.out.println("Reciever: "+ reciever);

Java POJO - ReadMessage.java

package com.autowirepkg;

public class ReadMessage {

	WriteMessage writeMsg; //will be autowired with bean having same name in XML

	public WriteMessage getWriteMsg() {
		return writeMsg;

	public void setWriteMsg(WriteMessage writeMsg) {
		this.writeMsg = writeMsg;
	public void readMsg(){

XML Configuration - appContextAutowire.xml

<?xml version="1.0" encoding="UTF-8"?>  

<bean id="writeMsg" class="com.autowirepkg.WriteMessage">
<constructor-arg index="0" value="You are excellent learner"></constructor-arg>
<constructor-arg index="1" value="tutorialsinhand"></constructor-arg>
<constructor-arg index="2" value="Readers"></constructor-arg>

<bean id="ReadMsgBean" class="com.autowirepkg.ReadMessage" autowire="byName">


Test Class - TestSpringClass

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

import com.autowirepkg.ReadMessage;

public class TestSpringClass {

	public static void main(String[] args) {		
		ApplicationContext context = new ClassPathXmlApplicationContext("appContextAutowire.xml");
		ReadMessage readMessage = (ReadMessage) context.getBean("ReadMsgBean");



Message: You are excellent learner
Sender: tutorialsinhand
Reciever: Readers




Please Share this page
Views : 74
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!