0

I'm writing a simple desktop JavaFX application, which has a service to retrieve Person objects:

import model.entities.Person;

public class PersonService {

    public List<Person> findAll() {
        (...)
    }
}

Then I'm writing a JavaFX controller which depends on PersonService, and I'd like to implement a simple dependency injection mechanism to make things decoupled:

import model.services.PersonService;

public class PersonDetailsController {

    private PersonService personService;

    public PersonDetailsController(PersonService personService) {
        this.personService = personService;
    }

    (...)

However, as the JavaFX application doesn't need me to explicitly instantiate the controllers, I don't know how I could provide a PersonService instance to my PersonDetailsController. So what is the proper way to inject a service instance to my desktop JavaFX application?

Nelio Alves
  • 1,231
  • 13
  • 34
  • 1
    Java uses the service provider mechanism for that. You would load your service with `private PersonService personService = ServiceLoader.load(PersonService.class).iterator().next();`. How you make PersonService implementations available will depend on whether your program is a Java module. – VGR Dec 22 '18 at 21:39
  • 1
    These may help: https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml and https://stackoverflow.com/questions/30814258/javafx-pass-parameters-while-instantiating-controller-class – Slaw Dec 22 '18 at 23:12

0 Answers0