Setter-based DI is performed by the container calling setters on beans after calling a no-argument constructor or a static
no-argument factory method to instantiate the bean.
The following example shows a class whose dependency can only be injected via a setter. This class is a regular Java class. It is a POJO (plain Java object) that does not depend on specific container interfaces, base classes, or annotations.
public class SimpleMovieLister {
// SimpleMovieLister depends on MovieFinder
private MovieFinder movieFinder;
// setter to allow the Spring container to implement MovieFinder
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// business logic that actually uses the embedded MovieFinder is omitted...
}
class SimpleMovieLister {
// lazy-initialized property that allows the Spring container to implement MovieFinder
lateinit var movieFinder: MovieFinder
// business logic that actually uses the embedded MovieFinder is omitted...
}
ApplicationContext
supports both constructor-based and setter-based DI for the beans it manages. It also supports setter based DI after some dependencies are already injected using the constructor approach. You configure dependencies in the form of BeanDefinition
, which you use in conjunction with PropertyEditor
instances to convert properties from one format to another. However, most Spring users work with these classes not directly (that is, programmatically), but rather with XML bean
definitions annotated components (that is, classes marked with the annotations @Component
,@Controller
and so on) or methods marked with the @Bean
annotation in Java-based classes marked with the @Configuration
annotation. These sources are then internally converted into BeanDefinition
instances and used to load the entire Spring IoC container instance.
GO TO FULL VERSION