@Override
  public void beforeTestMethod(SpringTestContext testContext) throws Exception {
    Object testInstance = testContext.getTestInstance();
    if (!(testInstance instanceof Specification)) return;

    if (Boolean.TRUE.equals(testContext.getAttribute(
      DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE))) {
      // we need to reinject the spies https://github.com/spockframework/spock/issues/1790
      injectSpies(testContext);
    }

    Specification specification = (Specification)testInstance;
    ScanScopedBeans scanScopedBeans = ReflectionUtil.getAnnotationRecursive(specification.getClass(), ScanScopedBeans.class);
    Set<String> scopes = scanScopedBeans == null
      ? emptySet()
      : new HashSet<>(asList(scanScopedBeans.value()));

    ApplicationContext applicationContext = testContext.getApplicationContext();
    String[] mockBeanNames = applicationContext.getBeanDefinitionNames();
    List<Object> mockedBeans = new ArrayList<>();

    for (String beanName : mockBeanNames) {
      BeanDefinition beanDefinition = ((BeanDefinitionRegistry)applicationContext).getBeanDefinition(beanName);
      if (beanDefinition.isAbstract() || beanDefinition.isLazyInit()) {
        continue;
      }
      if (beanDefinition.isSingleton() || scanScopedBean(scanScopedBeans, scopes, beanDefinition)) {
        Object bean = applicationContext.getBean(beanName);
        if (mockUtil.isMock(bean)) {
          mockUtil.attachMock(bean, specification);
          mockedBeans.add(bean);
        }
      }
    }

    testContext.setAttribute(MOCKED_BEANS_LIST, mockedBeans);
  }
This {@link TestExecutionListener} takes care of attaching and detaching the
mocks to the current {@link Specification}.

@author Leonard Bruenings
spock-spring/src/main/java/org/spockframework/spring/SpringMockTestExecutionListener.java