Spring autowiring byName real time example

Autowiring byName is similar to autowiring with byType. Here Spring will match the pojos and Properties injected into pojos by Spring container with the help of beans.xml by using its names. Lets see an example.


<pre>package com.sourceforopensource.pojos;

public interface LogWriter {
 public void write(String text);


package com.sourceforopensource.pojos;

public class ConsoleWriter implements LogWriter {

 public void write(String text) {



package com.sourceforopensource.pojos;

public class FileWriter implements LogWriter {

 public void write(String text) {
 // Write to a file here.
 // Dummy implementation
 System.out.println("Write to file: " + text);



package com.sourceforopensource.pojos;

 * Dummy implementation of logger.

public class Logger {

 private LogWriter consoleWriter;
 private LogWriter fileWriter;

//below method are expecting objects of type LogWriter.
 public void setConsoleWriter(LogWriter writer) {
 this.consoleWriter = writer;

 public void setFileWriter(LogWriter fileWriter) {
 this.fileWriter = fileWriter;
 public void writeFile(String text) {
 public void writeConsole(String text) {



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="logger" class="com.sourceforopensource.pojos.Logger"


 <bean id="consoleWriter" class="com.sourceforopensource.pojos.ConsoleWriter">

 <bean id="fileWriter" class="com.sourceforopensource.pojos.FileWriter">


package com.sourceforopensource.pojos;

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

public class App {

 public static void main(String[] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("com/sourceforopensource/beans/beans.xml");
 Logger logger = (Logger)context.getBean("logger");
 logger.writeConsole("Hello there");
 logger.writeFile("Hi again");



Hello there
Write to file: Hi again

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

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