Java Dependency Injection Simple Example

Today we’ll see a simple code that shows what actually Dependency Injection is.

Imaging that you have Student class, and several different loggers for this class. Each logger prints messages in his own particular way. You want to be able to choose the Logger type for each Student on its instantiation without touching anything inside Student class implementation.

Take a look at this code and I’m pretty sure you will get the main idea of Dependency Injection:

    public interface LoggerInterface {
        void WriteLog(String text);
    }

    public static class Student {
        public Student(LoggerInterface logger) {
            logger.WriteLog("New Student created");
        }
    }

    public static class LoggerOne implements LoggerInterface {
        public void WriteLog(String text) {
            System.out.println(text + " with LoggerOne");
        }
    }

    public static class LoggerTwo implements LoggerInterface {
        public void WriteLog(String text) {
            System.out.println("###################");
            System.out.println(text + " with LoggerTwo");
            System.out.println("###################");
        }
    }

 

Let’s instantiate two Student objects with different logger:
public static void main(String[] args) {
        Student employee1 = new Student(new LoggerOne());
        Student employee2 = new Student(new LoggerTwo());
    }

 

Output:

New Student created with LoggerOne
###################
New Student created with LoggerTwo
###################

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.