如何避免对依赖对象的依赖

How to avoid dependency about at dependent objects

我有一个关于 Spring 环境的问题。如果我有一个控制器,并且该控制器内部有很多相互依赖的服务,如果我更改了该控制器上的某些内容,我应该通过减少代码量来做什么 "less" ?到那时,我将如何避免依赖问题? ,希望我的问题对你来说很清楚。

谢谢

我的两分钱:

  • 使用 Spring 团队推荐的自动装配构造函数注入。当您的控制器变得臃肿时,这样做会使其非常明显(请参阅下一点)
  • 正如 Bob Martin 在他的 Clean Code 一书中所建议的那样,构造函数中的依赖项不超过 3 个。如果你有更多,那么你的控制器可能违反了单一职责原则。
  • 如果您希望您的控制器执行更多操作,那么您可能应该将该功能放在第二个控制器中!

一个粗略的例子:

    @RestController
    public class PetShopController {

    @Autowired private DogService dogService;
    @Autowired private CatService catService;
    @Autowired private MonkeyService monkeyService;
    @Autowired private FishService fishService;
// all three services above are dependent on the two below
    @Autowired private PetInsuranceService petInsuranceService;
    @Autowired private PetOwnerService petOwnerService; 

    //..and so on
    }

更改为:

@RestController
public class DogsController {

private DogService dogService;

//the insurance/owner services have been split into one service/pet type
private DogInsuranceService dogInsuranceService; 
private DogOwnerService dogOwnerService;

//I've used interfaces for types here
@Autowired DogsController(IPetService dogService,IInsuranceService dogInsuranceService, IOwnerService dogOwnerService) {
this.dogService = dogService;
this.dogInsuranceService = dogInsuranceService;
this.dogOwnerService = dogOwnerService;
}

//..and so on
// make similar controllers for other pets!!

}

我认为这不是要减少代码量,而是要确保每个 class 都有一个单一的职责!例如/这里狗会像狗一样吠叫!猫会像喵喵一样做猫事!!一旦你有一个 class 和超过 3 个 deps/services 两者都做或更多,那么 class 就需要拆分!!

controller has lots of services inside in it which is dependent each other

那是一种设计味道,您甚至可能会遇到这种设计的循环依赖问题。您可能需要在此处 post 您的控制器代码以获得更多帮助。