Spring Autowiring by Constructor

Spring provides us a feature to autowire the properties of constructor in pojo from beans.xml. Lets see the example.

LogWriter.java


package com.sourceforopensource.pojos;

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

ConsoleWriter.java

package com.sourceforopensource.pojos;

public class ConsoleWriter implements LogWriter {

 public void write(String text) {
 System.out.println(text);
 }

}

FileWriter.java

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);
 
 }

}

Logger.java

package com.sourceforopensource.pojos;

/*
 * Dummy implementation of logger.
 */

public class Logger {

 private LogWriter consoleWriter;
 private LogWriter fileWriter;
 
 public Logger(ConsoleWriter consoleWriter, FileWriter fileWriter) {
 this.consoleWriter = consoleWriter;
 this.fileWriter = fileWriter;
 }

 
 public void writeFile(String text) {
 fileWriter.write(text);
 }
 
 public void writeConsole(String text) {
 consoleWriter.write(text);
 }

}

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:p="http://www.springframework.org/schema/p"
 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"
 autowire="constructor">

 </bean>

 <bean name="consolewriter" class="com.sourceforopensource.pojos.ConsoleWriter">
 </bean>

 <bean id="filewriter" class="com.sourceforopensource.pojos.FileWriter">
 </bean>
 
</beans>

App.java

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");
 
 ((ClassPathXmlApplicationContext)context).close();
 }

}

output:

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 *