如何从Spring获取实例化的bean列表? [英] How can I get a list of instantiated beans from Spring?
问题描述
我在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的解决方案是没有用的,因为我有很多惰性bean,并且其中一些不能被实例化,因为这在某些测试中会失败(即,我有一个需要java.sql.DataSource
的bean,但是测试有效,因为他们不需要那个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屋!