mardi 29 novembre 2016

Count method invocations in Spring Service used by Bean

Suppose I have the following bean:

@Bean
public void consumer() {

   while(true) {
      String message = //blocked waiting for message to consume
      myService.processMessage(message);
    }

}

That uses the following service:

@Service
public class MyService {

    public void processMessage(String message) {

        //process the message

    }

}

which is autowired throughout the rest of the application. In my testing class I also autowire the service:

public class MyTest {

   @Autowired
   private MyService myService;

   (...)
}

Now, when the application is running and/or being tested by the MyTest class the consumer waits for messages and processes them with MyService.processMessage method. What I need is for MyTest to be able to count how many invocations are performed to MyService.processMessage method. Ideally, I would like to be able to do something like:

public class MyTest {

  @Autowired
  private MyService myService;

  @Before
  public void intersect() {

      ProxyFactory pf = new ProxyFactory(myService);
      pf.addAdvice((MethodInterceptor) invocation -> {
      if(invocation.getMethod().getName().startsWith("processMessage")) {
        //Do my count
      }
      return null;
    });

  }

}

Unfortunately, the above code excerpt does not work because the myService instance is autowired.

My question is: Does anyone know how to implement something in line with the latter code excerpt that actually works? Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire