Java:Spring引导类构造函数具有太多DI';s
假设我有一个Spring Boot类:Java:Spring引导类构造函数具有太多DI';s,java,spring-boot,dependency-injection,constructor,Java,Spring Boot,Dependency Injection,Constructor,假设我有一个Spring Boot类: public class SomeClass { private ApplicationContext applicationContext; private MessagingService messagingService; private ClientReportFactoryImpl clientReportFactory; private TerminalReportFactoryImpl terminalRep
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?您不应该在
应用程序
类中调用所有服务,有一个很好的指南(本章和以下章节),因此它可能看起来像这样:
com
+- example
+- myproject
+- Application.java
|
+- domain
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
基本上,您的
服务
与@Service
(显然)类似,因此它们将由@ComponentScan
在应用程序
中提取 根据您的应用程序,如果您需要定义依赖项,有一种更干净的方法可以通过使用Lombok注释来减少构造函数代码:@RequiredArgsConstructor(onConstructor_={@Inject})
这将自动注入定义为的所有依赖项
private final dependency 1 dep1代码>这实际上取决于您的整体应用程序结构。但通常认为依赖性太多是一种不好的做法。经常思考为什么在一个类中需要所有这些服务是一个好主意。单一责任原则——没有必要严格遵守,但要经常考虑这一点,这就是我想要做出改变的原因。我认为在一个类中有这么多DI是一个糟糕的设计。我需要重构,看看是否可以删除这个类的一些职责,并将它们委托给其他地方。为什么你甚至需要应用程序中的所有依赖项。通常,这应该只用于配置/引导,不应该包含逻辑。看起来您正在注入它们以用于其他@Bean
方法。这是正确的,但我认为最新版本的Spring不再需要这些。但我可能错了。我问的是一般每个班级的直接投资额。应用程序类在这里是一个糟糕的例子。我的错,我明白了。因此,我唯一能说的是——根据我个人的经验,每个类的注入次数不超过3次,否则我会开始考虑如何将这些依赖项外部化。但是,当我不得不运行一个可以使用多个表来收集数据的服务时,情况又如何呢。从理论上讲,由于队列的复杂性,我可以使用相当多的存储库。如果您也可以影响存储库的设计,您可以考虑在这里考虑聚合根,在这里,您可能会得到更少的存储库。至少我明白了,大多数时候我不需要为每个实体建立存储库。。。但不知道这是否对你的案例有帮助。也许你必须考虑微服务体系结构,并为每个微服务分配关注点。此外,你还必须意识到注射过多可能会成为SPOF。可测试性将是困难的,因为您必须模拟尽可能多的服务,因为您注入的服务甚至会使测试代码不可读。