如何从 Spring 获取实例化 bean 的列表? [英] How can I get a list of instantiated beans from Spring?

查看:54
本文介绍了如何从 Spring 获取实例化 bean 的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Spring 上下文中有几个 bean 具有状态,因此我想在单元测试之前/之后重置该状态.

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

我的想法是向一个辅助类添加一个方法,该类只遍历 Spring 上下文中的所有 bean,检查用 @Before@After 注释的方法> 并调用它们.

My idea was to add a method to a helper class which just goes through all beans in the Spring context, checks for methods that are annotated with @Before or @After and invoke them.

如何从 ApplicationContext 获取实例化 bean 的列表?

How do I get a list of instantiated beans from the ApplicationContext?

注意:简单地迭代所有定义的 bean 的解决方案是无用的,因为我有很多惰性 bean,其中一些不能被实例化,因为这会在某些测试中失败(即我有一个需要 java.sql.DataSource 但测试工作,因为他们不需要那个 bean).

Note: Solutions which simply iterate over all defined beans are useless because I have many lazy beans and some of them must not be instantiated because that would fail for some tests (i.e. I have a beans that need a java.sql.DataSource but the tests work because they don't need that bean).

推荐答案

例如:

 public static List<Object> getInstantiatedSigletons(ApplicationContext ctx) {
            List<Object> singletons = new ArrayList<Object>();

            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;

    }

这篇关于如何从 Spring 获取实例化 bean 的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆