Approach 3: Dependency Injection

  • Use annotations to indicate that a class can be injected
  • Spring will pass you an instance of a class
public class ImportantProcessHandler {

    public ImportantProcessHandler(Logger logger) {
        this.myLogger = logger;
    }

    public void handleImportantProcess() {
        myLogger.log("Done!");
    }
}

@Component
public class StandardOutLogger implements Logger {
    public void log(String message) {
        System.out.println(message)
    }
}

27 / 27