Spring 中的依赖注入使用注解

Dependecy injection in Spring using annotations

依赖注入的主要概念——据我所知——是 "design for interfaces" 使依赖组件彼此松散耦合的做法。但是,我已经看到许多使用 Spring 开发的系统,在我看来,它们违反了这个概念 [并且 Spring Container 在语法级别允许这样做]。在看到 code/implementation.

之后,我开始质疑我的 knowledge/understanding 依赖注入概念

我经常看到组件自动连接到彼此的具体实现,我的意思的一个例子:

@RestController
public class MyRestController {
    @AutoWired
    private MyServiceOne serviceOne;
    // .. rest of the code if the rest controller here ...
}
@Service
public class MyServiceOne {
    @Autowired
    private MyRepository repo;
    // rest of code of the service here
}

如您所见,"MyServiceOne" 是一个具体的 class,而不是一个接口,Spring 框架可以接受。不需要在“@Configuration”class 某处提供“@Bean”方法来注入正确的具体 class 类型 [因为 @service 已经是具体的 class].

因此,对于服务层中的任何 change/customization [控制器中注入的依赖项],我将不得不更改控制器中的以下行:

@AutoWired
private MyServiceOne serviceOne; //change this to be another service class, or a service class that extends it

这不是松耦合! [或者是吗?] 在我看来,如果我们要以这种方式使用 Spring DI,最好根本不要使用它!在应用程序内存中创建了很多 maven/Gradle 依赖项和 运行-time 对象!

我想知道,在我对依赖注入如何作为 concept/or 如何 Spring 处理依赖注入的理解中是否缺少某些东西?

感谢您的指导!

使用接口通常是最佳实践,您通常应该在自己的代码中更喜欢它(连同构造函数注入而不是此字段注入),但荒谬地纯粹主义关于允许的内容会适得其反。

例如,我正在使用 Amazon DynamoDB,我需要注入一个 DynamoDB class 实例。我真的更希望能够注入一个接口,但是亚马逊的 SDK 没有提供接口,并且能够注入 class 的配置实例仍然比什么都不注入要好得多。

类似地,使用 Spring Boot 注入 @ConfigurationProperties bean 并不少见,它们基本上是没有逻辑的类似结构的 POJO。在这种情况下,定义一个接口只会浪费时间,但是通过(具体)类型注入 bean 的能力非常有用。