如何在 Spring Boot 应用程序中正确使用依赖注入?
我的软件有一个 JavaFX 主窗口和多个从主窗口打开和关闭的子对话框。我需要在 Spring Boot 注入的子对话框中使用 REST 客户端。但是,每个客户端实例都需要一个构造函数参数进行初始化。
因此,我最终在主窗口的控制器中拥有大量 REST 客户端,然后将它们传递到子对话框的控制器。有没有更好的方法来实现这个以摆脱所有构造函数参数?
@Component
@Scope("prototype")
public class MainController {
private final FirstClient first;
private final SecondClient second;
private final ThirdClient third;
@Autowired
public MainController(FirstClient first, SecondClient second, ThirdClient third) {
this.first = first;
this.second = second;
this.third = third;
}
private void openSubDialog() {
// ...
SubController subController = new SubController(first, second);
// ...
}
private void openAnotherSubDialog() {
// ...
AnotherSubController anotherSubController = new AnotherSubController(first, third);
// ...
}
}
我的控制器类用
@Component
和 @Scope("prototype")
注释。
@Component
@Scope("prototype")
public class SubController {
private final FirstClient first;
private final SecondClient second;
@Autowired
public SubController(FirstClient first, SecondClient second) {
this.first = first;
this.second = second;
}
private void doSomething() {
var result = first.callSomeService();
}
}
最后,我的 REST 客户端看起来有点像这样:
@Service
public class FirstClient {
public SomeType callSomeService() {
return restClient.getSomeData();
}
}
我正在寻找一种方法来直接将 REST 客户端注入子对话框的控制器中,而不需要添加构造函数参数并将它们从主视图传递下来。在伪代码中,类似这样:
@Component
@Scope("prototype")
public class ImprovedController {
@InjectHereDirectly
private final FirstClient first;
@InjectHereDirectly
private final SecondClient second;
// No constructor needed
private void doSomething() {
var result = first.callSomeService();
}
}
您可以使用
Lombok
库来实现这一点。
第 1 步:包含 Lombok 依赖项:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>...</version>
</dependency>
第2步:像这样使用它:
@RequiredArgsConstructor
public class UiController {
private final TodoRepository todoRepository;
}
此 git 存储库中提供了工作模板应用程序:
https://github.com/davidweber411/javafx-JavaFxSpringBootMavenApp