IoC

24 Jun 2023 . spring .


Dependency Injection

Without dependency injection

We creates a dependency between the Client and the ExamplieService. We are instantiating ExamplieService every time we call Client(), which means the Client class directly depends on the ExamplieService class.

public class Client {

private ExampleService service;

    Client() {
        service = new ExampleService();
    }
}

Constructor Injection

We create an abstraction by having the ExamplieService dependency class in Client’s constructor signature (not initializing dependency in class).

Constructor injection allows injecting values to immutable fields and makes testing easier.

public class Client {

private ExampleService service;

    Client(Service service) {
        this.service = service;
    }
}

This allows us to call the dependency then pass it to the Client class like so:

ExampleService service = new ExampleService(); // dependency
Client client = new Client(service);

Setter Injection

public void setService(Service service) {
		this.service = service;
}

Interface Injection

public interface ServiceSetter {
		public void setService(Service service);
}

public class Client implements ServiceSetter {
		private Service service;

		@Override
		public void setService(Service service) {
				this.service = service;
    }
}