我对Spring Environment有疑问。如果我有一个控制器,并且该控制器内部有很多相互依赖的服务,并且如果我在该控制器上进行了某些更改,我应该通过减少代码量“做些什么”?这样,我将如何避免依赖问题? ,希望我的问题对您来说很清楚。
谢谢
我的两分钱:
粗略的例子:
@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个以上部门/服务同时完成两个或多个课程,那么该班级就需要拆分!
控制器内部有很多服务,每个都其他
这是一种设计气味,您甚至可能会遇到这种设计的循环依赖问题。您可能需要在此处发布控制器代码以获取更多帮助。