3

I have maven module_A service rom where i need to call module_B service. Intention is to keep the coupling minimum

  1. Approach1:- This is approach we are generally used to. module_B will be injected under module_A and the call service_B from service_A. But it tightly couples the module_B with module_A.

  2. Approach2:- Spring events like this example. With this approach listener can be in module_A. For example :- I need to call module_A(EmployeeService.findEmployee(int id)) from module_B. What i can do is i will create EmployeeFinderCustomEvent which will contain employeeId. Event will be published from module_B.

EmployeeFinderCustomEventListener will lie under module_A and find the employee. But I need to return Employee object from listener which should be returned to module_B calling service. But onApplicationEvent return type is void..

     @Override
        public void onApplicationEvent(EmployeeFinderCustomEvent cse) {
            // find employee
        }

How can I return the object from spring event listener to caller to achieve loose coupling?

user3198603
  • 5,528
  • 13
  • 65
  • 125
  • You won’t “return” anything, you’d publish another event. The whole point of returning an object indicates a caller waiting somewhere, which the opposite of event-based model. – Abhijit Sarkar Nov 05 '22 at 05:29

1 Answers1

0

Application Events are not intended to work that way.

You can place EmployeeService interface in separate module that both A & B depend on, and keep implementation (EmployeeServiceImpl or whatever) in module A. This solution will not require module B to be dependent on module A.

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
  • 1
    what you posted is dependency inversion. But that way my module B will still dependent on abstract modules containing interfaces (which may be large in number). Is there a way i completely decouple them with spring(spring events are close but does not return object) ? – user3198603 May 01 '18 at 02:30