All Dependency Injection Types [Spring]

No, the dependency will be still perceived as a singleton unless we indicate the existence of this special dependency type.

Returning back to practice, we have again 3 services, one of them is depending on others, service2 is the usual object which can be injected in DependentService by any of previously described dependency injection techniques, let’s say setter injection.

The object of Service1 will be different, it can not be injected once, a new instance should be accessed with each call — let’s create a method that will provide this object and let Spring know about it.

We haven’t declared an object of Service1 as a usual dependency, instead, we’ve specified method which will be overridden by Spring framework in order to return the latest instance of Service1 class.

Method-provider of dependency doesn’t have to be abstract and protected, it can be public and contain implementation but keep in mind that it will be overridden in a subclass, created by Spring.

We are again in pure XML configuration example, so we will have to indicate first that service1 is an object with a short lifetime, in Spring terms we can use here prototype scope as it is smaller than a singleton.

By lookup-method tag, we can indicate the name of the method, which will inject dependency.

The same can be done in an annotation based way.

Disadvantages and AdvantagesIt won’t be correct to compare this type of dependency injection with others as it has an absolutely different use case.

ConclusionWe went through 4 types of dependency injection implemented by Spring framework:Constructor injection — good, reliable and immutable, inject via one of the constructors.

Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.

Setter injection — more flexible, mutable objects, injection via setters.

Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.

Field injection — fast and convenient, coupling with IoC container.

Possible to configure in XML+Annotations, Java + Annotations.

Lookup method injection — totally different from others, used for injection dependency of smaller scope.

Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.

Despite constructor tends to be recommended way I would advise you to clarify your needs first, maybe setter of field injection would be more appropriate for your application.

In any case, you can always mix different approaches and achieve your goals.

.. More details

Leave a Reply