It is very common in the development of Java applications to have dependency injections of the same bean in different locations and often in relationships between beans as in the examples below:
@Service @RequiredArgsConstructor public class PersonUpdater { private final PersonValidator validator; private final DocumentService documentService; //outras utilizações no fluxo de atualização public Person toUpdate(final Person person) { validator.validate(person); //...fluxo de atualização de pessoa return person; } }
@Component @RequiredArgsConstructor public class PersonValidator { private final DocumentService documentService; public void validate(final Person person) { if (person.isAdult() && person.isMale()) { final var documents = documentService.getMilitaryDocuments(person.getId()); //validações necessárias } } }
The bean DocumentService was injected into both PersonUpdater and PersonValidator . In PersonUpdater the bean can be used for other update flows, however, in PersonValidator the bean will be ONLY used to search for military documents WHEN it is the update of a male person of legal age. One possibility of having the same result are the examples below:
@Service @RequiredArgsConstructor public class PersonUpdater { private final PersonValidator validator; private final DocumentService documentService; //outras utilizações no fluxo de atualização public Person toUpdate(final Person person) { validator.validate(person, () -> documentService.getMilitaryDocuments(person.getId())); //...fluxo de atualização de pessoa return person; } }
@Component @RequiredArgsConstructor public class PersonValidator { public void validate(final Person person, final Supplier<List<Document>> documentsSupplier) { if (person.isAdult() && person.isMale()) { final var documents = documentsSupplier.get(); //validações necessárias } } }
With Functional Interfaces, a range of options for using the behaviors of a Java application opens up! They make use more flexible via method arguments (as in the example) and via attributes of some class.
In addition to dependency injection only being done in one place, we have:
The above is the detailed content of Dica Java: Functional Interface #. For more information, please follow other related articles on the PHP Chinese website!