Announcement Announcement Module
Collapse
No announcement yet.
Is it possible to read the bean definitions without initializing the context? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • 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:
    Code:
    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:
    Code:
    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 org.springframework.context.support.AbstractRefres hableApplicationContext.getBeanFactory(AbstractRef reshableApplicationContext.java:171)


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

    Thanks a lot in advance,
    Hernan

  • #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) {
    @Override
    public void refresh() throws BeansException, IllegalStateException {
    refreshBeanFactory();
    }
    };
    ctx.refresh();
    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.

    Thanks,
    Hernan

    Comment

    Working...
    X