Kushang
Kushang

Reputation: 78

filter for services with guice injector in MVC architecture

We have several modules, each with few services. We are using play framework and it works well with juice dependency injector.

for example,

For module x,

@implementedBy(XI1Impl.class)
interface XI1 {....}


class XI1Impl implements XI1
{....}

Now, we need to add a common check API before invoking any service API. The simplest way is to add check call inside the method implementation for each API for each service for each module.

Is there any better way to add a common check for services so consumer application when injecting any of service and call any service API first the check call should execute.

Does Guice has any annotation or any way to configure check API call such that while injecting service it will first execute specific call.

In play framework, filter class can do the same job for the controller, but I do not have any idea if similar concept present at the service level.

Please suggest me if it is possible to write logic, which can do common checks for all the methods of selected service without modifying its service APIs implementation.

Thanks in advance.

Upvotes: 0

Views: 115

Answers (1)

Arpit Suthar
Arpit Suthar

Reputation: 754

It seems you want to run some piece of code before calling your service function, try this.

  1. You need to create a class and a function which will contain your function which will run everytime before your actual service call

    class FilterService {
        def apply(block: => Any => Any) = {
            println("This block will run before actual function call.")
            block()
        }
    }
    
  2. Now you have to use this in your service

    class ActualService @Inject()(filterService: FilterService){
        def actualFunction(str: String) = filterService.apply { data =>
            // `data` you can use if you are returing anything from your filter service function.
            println("In actual function calling.")
            str
        }
    }
    

Hope it helps :)

Upvotes: 0

Related Questions