弹簧中的松耦合和 DI 的作用

问题描述 投票:0回答:1

我是 Spring 新手,目前正在通过一些付费课程学习它。我遇到了松耦合的概念,并且我了解 Spring 提倡在接口中定义行为。但是,我想知道为什么需要在接口中定义行为而不是直接扩展类中的实现?

例如,代替:

public class Car extends PetrolEngine {
    // implementation
}

为什么建议定义这样的接口:

public interface Engine {
    void start();
}

public class PetrolEngine implements Engine {
    public void start() {
        // implementation
    }
}

public class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}

在这种情况下使用接口有哪些优点?这对 Spring 中的松散耦合有何帮助?

java spring
1个回答
0
投票

简单回答:

Spring DI 通过接口确保您的代码是:

  • Unit Testable
  • Reusable

例如:

public interface Engine {
    void start();
}

public class PetrolEngine implements Engine {
    public void start() {
        // implementation
    }
}

public class DieselEngine implements Engine {
    public void start() {
        // implementation
    }
}

@Component
public class Car {
    
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }
}

@Configuration
public class CarConfig {

   @Bean
   public Engine engine() {
      return new PetrolEngine(); // or new DieselEngine based on requirement. This ensures loose coupling.
   }

}
© www.soinside.com 2019 - 2024. All rights reserved.