7.4.1 Setter-based dependency injection

时间:2022-09-02 09:57:53

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.

在调用一个无参构造器或无参的静态工厂方法区实例化你的bean后,基于Setter的依赖注入能够熟练的通过调用你的beans的setter方法.

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.

下面的例子展示了一个只能够使用纯粹的setter注入的类.这是一个标准的Java类.他是普通的Java对象,它没有依赖于容器中特定的接口,基类或注解.

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.

 ApplicationContext 能够它管理的beans支持基于构造器和基于setter的依赖注入.它也支持在一些依赖已经通过构造器的方法被注入后进行基于setter的依赖注入.你以 BeanDefinition的形式配置依赖,你结合使用 PropertyEditor 实例将属性从一种格式转换到另一种格式.然而,大多数Spring用户不会直接使用这些类(也就是说,以编程的方式)而去使用XML bean定义,注解组件(也就是说,在类上加 @Component@Controller等等)或者使用基于java的 @Configuration 类的 @Bean 方法.这些源由 BeanDefinition 内部转化为实例和载入一个空的Spring IoC容器实例.