如何避免依赖于依赖对象

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

我对Spring Environment有疑问。如果我有一个控制器,并且该控制器内部有很多相互依赖的服务,并且如果我在该控制器上进行了某些更改,我应该通过减少代码量“做些什么”?这样,我将如何避免依赖问题? ,希望我的问题对您来说很清楚。

谢谢

spring dependency-injection dependencies dependency-management
2个回答
0
投票

我的两分钱:

  • 使用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!!

}

我认为这不是在减少代码量,而是在确保每个类都负有单一责任!例如,这里的狗会做狗吠之类的东西!猫会像猫一样发出猫的声音!!一旦您的班级拥有3个以上部门/服务同时完成两个或多个课程,那么该班级就需要拆分!


0
投票

控制器内部有很多服务,每个都其他

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

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