How can I get a list of instantiated beans from Spring?

前端 未结 6 773
挽巷
挽巷 2020-12-05 07:50

I have several beans in my Spring context that have state, so I\'d like to reset that state before/after unit tests.

My idea was to add a method to a helper class wh

6条回答
  •  臣服心动
    2020-12-05 08:30

    Using the previous answers, I've updated this to use Java 8 Streams API:

    @Inject
    private ApplicationContext applicationContext;
    
    @Before
    public void resetMocks() {
        ConfigurableListableBeanFactory beanFactory = ((AbstractApplicationContext) applicationContext).getBeanFactory();
        Stream.of(applicationContext.getBeanDefinitionNames())
                .map(n -> beanFactory.getSingleton(n))
                // My ConfigurableListableBeanFactory isn't compiled for 1.8 so can't use method reference. If yours is, you can say
                // .map(ConfigurableListableBeanFactory::getSingleton)
                .filter(b -> Mockito.mockingDetails(b).isMock())
                .forEach(Mockito::reset);
    }
    

提交回复
热议问题