1
votes

I'd like to ask is there anyway to detect all beans have been instantiated in Spring framework ?

I'm using FileSystemXmlApplicationContext class of Spring library to load in my Spring configuration XML.

I do understand that I can get all beans after they are been instantiated in bean factory. My dumb solution is by using getBean(String name) method in Spring API and check against with all desired beans in the Spring configuration XML. If all desired beans can be found, I can infer that all beans have been instantiated.

The reason I don't prefer the dumb solution is anytime I update my configuration XML, I need to update my source code of checking against again. If this solution has more vulnerabilities, please feel free to point out.

Thanks your time and kindly suggestions

2
when you start your application in the console you can see your spring beans. You can check that by searching for a known bean - Federico Piazza
@Fede Is that my dumb solution perform? - ShadowScorpion
I don't understand why you are checking if the bean is instantiated. Do you not trust spring? Or trust the xml you write? - ndrone
@ohiocowboy Good query, I'm trust Spring and already tested the XML I wrote. Worked fine. But I need to let my system deleted those configuration XML files after all beans have been successfully loaded and instantiate. This a consideration from security concern. - ShadowScorpion

2 Answers

1
votes

You can add a BeanPostProcessor to your context

class B1 implements BeanPostProcessor {
    List beans = new ArrayList();
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        beans.add(bean);
        return bean;
    }

    List getBeans() {
        return beans;
    }
...
0
votes

What about using getBeansOfType(Object.class)?

You will get a map containing all name-bean pairs in the application context. The is also a version to include non singletons, but you will get top level beans only.