Spring 如何将 class 与接口分离?

How does Spring decouple a class from an interface?

在 Spring 框架的官方网站上,有一个例子展示了 Spring 如何将 class 与接口分离,或者更确切地说,一个接口的实现。

代码如下:

接口:

package hello;

public interface MessageService {
    String getMessage();
}

组件Class:

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessagePrinter {

    final private MessageService service;

    @Autowired
    public MessagePrinter(MessageService service) {
        this.service = service;
    }

    public void printMessage() {
        System.out.println(this.service.getMessage());
    }
}

申请:

package hello;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan
public class Application {

    @Bean
    MessageService mockMessageService() {
        return new MessageService() {
            public String getMessage() {
              return "Hello World!";
            }
        };
    }

  public static void main(String[] args) {
      ApplicationContext context = 
          new AnnotationConfigApplicationContext(Application.class);
      MessagePrinter printer = context.getBean(MessagePrinter.class);
      printer.printMessage();
  }
}

我目前对依赖注入的理解是,当一个名为 A 的 class 需要另一个名为 B 的 class 来处理它必须做的事情时,B 是依赖关系,A 是依赖关系。如果 B 是一个接口,那么 A 依赖于 some 实现 B.

那么,在上面的代码中,MessagePrinter 是如何与 MessageService 实现分离的?

我们还得实施MessageService,如果不实施,MessagePrinter能正常发挥作用吗?

此致

是的,您的上下文中必须有一个 MessageService。没有它,由 @Autowired 注释引起的依赖注入将在上下文初始化期间失败。

如果我对术语的理解正确,MessagePrinter 不能与 MessageService 分离,因为前者在其代码中直接使用后者。但它可以与 MessageService 实现分离。

它与MessageService实现解耦,因为它只依赖于MessageService接口;它对实现 类.

一无所知

如果您碰巧有 MessageServiceImpl1 然后将其更改为 MessageServiceImpl2,则 MessagePrinter 根本不需要更改(如果两个实现在合同方面的行为相同,当然)。