【发布时间】:2018-07-21 22:08:03
【问题描述】:
在Spring框架的官方网站上,有一个例子展示了Spring如何将类与接口解耦,或者更好的说,如果是接口,则为实现。
代码如下:
界面:
package hello;
public interface MessageService {
String getMessage();
}
组件类:
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 的类需要另一个名为 B 的类来处理它必须执行的任何操作时,B 是一个依赖项,A 是一个依赖项。如果B 是一个接口,那么A 依赖于B 的一些 实现。
那么,在上面的代码中,MessagePrinter 如何与MessageService 实现解耦?
我们还是要实现MessageService,如果不实现,MessagePrinter能正常工作吗?
问候
【问题讨论】:
-
我想你在找
@Qualifier,见Autowiring spring bean by name using annotation -
@ElliottFrisch 我不知道
@Qualifier是什么。我刚开始学习spring,例子在网站的第一页。我不明白MessagePrinter是如何与MessageService的实现分离的 -
点击我提供的链接。在您的示例代码中,如何
MessagePrinter绑定到特定MessageService?注意@Autowired注释。就是这样。 -
@ElliottFrisch 我很困惑!你是什么意思绑?你的意思是
MessagePrinter是如何依赖于MessageService的?!!让我问一个问题,术语decoupling,是不是意味着MessagePrinter不再需要MessageService的实现了?如果不是,那我还没看懂! -
它不是的意思。这意味着它没有与特定实现耦合(绑定、链接、硬编码);您可以将
MessageService替换为MessageService的任何其他实现。或模拟MessageService,如您的示例。
标签: java spring spring-mvc dependency-injection decoupling