Posting beans to a TestNG listener that implements IInvokedMethodListener

I have a TestNG listener that implements IInvokedMethodListener . I would like to connect to the Spring bean inside this listener and use it. Unfortunately, this class is instantiated by TestNG, so Spring cannot connect anything in this annotated with @Autowired . I tried to implement ApplicationContextAware , but this does not work either.

Is there a way to connect Spring beans to classes that implement IInvokedMethodListener ?

+4
source share
1 answer

ApplicationContextAware only works for Spring Beans. You can use @Configurable , but this requires AspectJ.

Here is a simple hack that should work: add a static member to your listener class and enter it through a non-static setter.

 public class MyMethodListener implements IInvokedMethodListener { private static MyBean myBean; @Autowired public void setMyBean(MyBean myBean) { MyMethodListener.myBean = myBean; } } 

Include the bean of the required type in the application context.

The listener created with TestNG will not be the same instance as the Spring context, but it will have a static member set, provided that the context creation is complete before TestNG creates the listener instance.

+1
source

All Articles