Announcement Announcement Module
No announcement yet.
Is it possible to read the bean definitions without initializing the context? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Is it possible to read the bean definitions without initializing the context?

    Hi everyone,

    I need to read the bean definitions of a set of Spring configuration files without instantiating the beans.
    The purpose of this is to go through the bean definitions and detect which beans contain properties whose values came from a placeholder.

    My initial attempt was this, which loads the context in the first line:
    AbstractRefreshableApplicationContext ctx = new FileSystemXmlApplicationContext("c:\\tmp\\ctx.xml");
    DefaultListableBeanFactory bf = (DefaultListableBeanFactory) ctx.getBeanFactory();
    However, I can't initialize the context since there are beans that have a constructor argument that require having a valid value upon instantiation, and the placeholder's format makes that validation fail.

    My second attempt was this, which lazily loads the context:
    AbstractRefreshableApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {"ctx.xml"}, false);
    DefaultListableBeanFactory bf = (DefaultListableBeanFactory) ctx.getBeanFactory();
    But that code causes this exception:
    java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
    at hableApplicationContext.getBeanFactory(AbstractRef

    Is there a way to read the context configuration without the initialization of the context?

    Thanks a lot in advance,

  • #2
    I solved this issue by extending the FileSystemXmlApplicationContext and overriding the refresh() method to call only refreshBeanFactory();
    This allows me to do the following:

    AbstractRefreshableApplicationContext ctx= new FileSystemXmlApplicationContext(new String[] {"ctx.xml"}, false) {
    public void refresh() throws BeansException, IllegalStateException {
    DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ctx.getBeanFactory();

    This way the context loads the bean factory, and doesn't instantiate the beans, allowing me to read the bean factory definitions.