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

前端 未结 6 762
挽巷
挽巷 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:23

    For example:

     public static List getInstantiatedSigletons(ApplicationContext ctx) {
                List singletons = new ArrayList();
    
                String[] all = ctx.getBeanDefinitionNames();
    
                ConfigurableListableBeanFactory clbf = ((AbstractApplicationContext) ctx).getBeanFactory();
                for (String name : all) {
                    Object s = clbf.getSingleton(name);
                    if (s != null)
                        singletons.add(s);
                }
    
                return singletons;
    
        }
    
        

    提交回复
    热议问题