gpt4 book ai didi

Java:Spring Boot 类构造函数有太多 DI?

转载 作者:行者123 更新时间:2023-11-30 07:05:23 24 4
gpt4 key购买 nike

假设我有一个 Spring Boot 类:

public class SomeClass {

private ApplicationContext applicationContext;
private MessagingService messagingService;
private ClientReportFactoryImpl clientReportFactory;
private TerminalReportFactoryImpl terminalReportFactory;
private XMLView xmlView;
private PrepareXMLService prepareXMLService;

我在该类中有一个构造函数:

@Autowired
public SomeClass (ApplicationContext applicationContext, MessagingService messagingService, ClientReportFactoryImpl clientReportFactory,
TerminalReportFactoryImpl terminalReportFactory,
XMLView xmlView,
PrepareXMLService prepareXMLService) {
Assert.notNull(applicationContext, "ApplicationContext must not be null!");
this.applicationContext = applicationContext;
Assert.notNull(messagingService, "MessagingService must no be null!");
this.messagingService = messagingService;
Assert.notNull(clientReportFactory, "ClientReportFactory must not be null!");
this.clientReportFactory = clientReportFactory;
Assert.notNull(terminalReportFactory, "TerminalReportFactory must not be null!");
this.terminalReportFactory = terminalReportFactory;
Assert.notNull(xmlView, "XMLView must not be null!");
this.xmlView = xmlView;
Assert.notNull("PrepareXMLService must not be null");
this.prepareXMLService = prepareXMLService;
}

在类构造函数中使用这么多依赖项是否被认为是不好的做法?我是否应该重构我的类,以便构造函数中只有 1-2 个 DI?

最佳答案

您不应该直接在 Application 类中调用所有服务,how to structure your code 有一个很好的指南(这一章和后续章节)所以它可能看起来像这样:

com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java

基本上,您的服务annotated with attributes就像 @Service (显然),这样它们就会被 Application 中的 @ComponentScan 拾取。

关于Java:Spring Boot 类构造函数有太多 DI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com