Reputation: 6195
I have a question about Spring Environment. If I have a controller and that controller has lots of services inside in it which is dependent each other and if I change something on that controller what I should do "less" by reducing amount of codes ? By that, how I will avoid dependency problem ? ,Hope my question is clear for you .
Thank you
Upvotes: 0
Views: 169
Reputation: 16465
controller has lots of services inside in it which is dependent each other
That's a design smell right there, you might even get circular dependency problem with that kind of design. You may need to post your controller code here to get more help.
Upvotes: 0
Reputation: 970
My two cents:
A crude example:
@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
}
Change to:
@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!!
}
I'd argue that it's not about reducing the amount of code, it's more about making sure each class has a single responsibility! Eg/ here Dogs do dog things like bark! Cats do cat things like meow!! As soon as you have a class with more than 3 deps/services that does both or more then that class needs to be split!!
Upvotes: 1