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

标签 java spring-boot dependency-injection constructor

假设我有一个 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/

相关文章:

java - 如果 String 为空,如何设置 null 值?

java - 秒表基准测试是否可以接受?

java - 如何配置tomcat每次都重新部署war?

java - 将数据库中的值添加到 logback 日志消息

java - 即使设置了 spring.expression.compiler.mode,Spring SpEL 也不会编译

java - Spring 的 Autowiring 、新操作符和困惑

php - Symfony2 : Inject current user in Service

entity-framework - Global.asax 中的 MVC、 Entity Framework DBContext 连接

java - HK2 IterableProvider 命名方法找不到实现

java - 在嵌入式Tomcat 8.0.3和tomcat 7.0.53之间建立websocket连接