2020-02-14

Spring 5 - Setter-based dependency injection

Setter-based dependency injection 


Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. The following example shows a class that can only be dependency-injected using pure setter injection. This class is conventional Java. It is a POJO that has no dependencies on container specific interfaces, base classes or annotations.

public class SimpleMovieLister { 
// the SimpleMovieLister has a dependency on the MovieFinder 
 private MovieFinder movieFinder; 
 // a setter method so that the Spring container can inject a MovieFinder 
 public void setMovieFinder(MovieFinder movieFinder) { 
 this.movieFinder = movieFinder; 
 } 
 // business logic that actually uses the injected MovieFinder is omitted... 
}

The ApplicationContext supports constructor-based and setter-based DI for the beans it manages. It also supports setter-based DI after some dependencies have already been injected through the constructor approach. You configure the dependencies in the form of a BeanDefinition, which you use in conjunction with PropertyEditor instances to convert properties from one format to another. However, most Spring users do not work with these classes directly (i.e., programmatically) but rather with XML bean definitions, annotated components (i.e., classes annotated with @Component, @Controller, etc.), or @Bean methods in Java-based @Configuration classes. These sources are then converted internally into instances of BeanDefinition and used to load an entire Spring IoC container instance.


No comments:

Post a Comment