Spring依赖注入的通用类型用法

时间:2019-08-22 23:02:22

标签: java spring oop dependency-injection solid-principles

在使用通用类型使用Spring依赖项注入的情况下,我对SOLID设计原则有疑问。我有下一个通用接口:

public interface EmailChecker<T> {
    boolean check(T message);
}

然后我有两种实现:一种用于生产,一种用于临时环境

@Profile("!production")
@Component
public class EmailRequestCheckerStaging implements EmailChecker<EmailRequest> {
    @Override
    public boolean check(EmailRequest message) {
        //TODO: some code here;
        return result;
    }
}

@Profile("production")
@Component
public class EmailRequestCheckerProduction implements EmailChecker<EmailRequest> {
    @Override
    public boolean check(EmailRequest message) {
        //TODO: some code here;
        return result;
    }
}

最后是'emailChecker'字段的依赖项注入:

@Service
public class Receiver {
  @Autowired
  private EmailChecker<EmailRequest> emailChecker;

  public void receiveMessage(EmailRequest dto) {
        if(emailChecker.check(dto)) {
            //TODO: some logic here
        }
  }

}

问题:这种依赖注入是否遵循所有SOLID原则?
注意:我有多个具有不同类型的'EmailChecker'接口的实现(为简单起见,我介绍了'EmailRequest'DTO实现)

1 个答案:

答案 0 :(得分:0)

基于意见的情况下,应该通过构造函数注入来显式注入注入的依赖项。

@Service
public class Receiver {  
  private EmailChecker<EmailRequest> emailChecker;

  @Autowired //could actually be omitted since class has only one constructor
  public Receiver(EmailChecker<EmailRequest> emailChecker) {
    this.emailChecker = emailChecker;
  }

  public void receiveMessage(EmailRequest dto) {
    if(emailChecker.check(dto)) {
        //TODO: some logic here
    }
  }
}

以便Receiver类的使用者知道它需要什么才能使其正常运行

具有显式依赖关系的类更诚实地了解他们的需求。他们非常清楚地说明了执行特定功能所需的条件。