Pivotal Knowledge Base

Follow

Obtaining the List of Resources Read by Spring Framework ApplicationContext

Environment

 Product  Version
 Spring  All

Overview

To create an application context, you must specify an XML Spring configuration file name. For example:

classpath*:/META-INF/spring/myapplicationconfig.xml

However, when there is more than one XML config file, it is tedious to have to specify the file names one by one:

classpath*:/META-INF/spring/conf*.xml

This article provides information on obtaining the file name and path of the XML configuration files used to initialize beans during ApplicationContext creation. The first step you may take is to is extend an application context and override the getConfigResources.

MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext { @Override protected Resource[] getConfigResources() { return super.getConfigResources(); }

On your application code, use the class above to getConfigResources. See the sample below:

MyClassPathXmlApplicationContext ctx= new MyClassPathXmlApplicationContext(); ctx.setAllowBeanDefinitionOverriding(false); ctx.setConfigLocation("classpath*:/META-INF/spring/conf*.xml"); ctx.afterPropertiesSet(); Resource r[]= ctx.getConfigResources();

Now checking Resource r[]= ctx.getConfigResources() reveals a NULL value. Discussed here is a workaround on getting the actual list instead of NULL.

Description

An Interfact ApplicationContext is a ResourcePatternResolver that can be used to resolve a pattern of resources, but not for storing these resources internally. It does not hold all the resources as an internal list; they are resolved at run time, and the beans that are created are based on the resolved resources.

The described way of getting these resources will not work, as the default implementation for that method returns NULL.

To resolve this issue using ResourcePatternResolver, use the sample solution below:

ApplicationContext ctx = new ClassPathXmlApplicationContext("..."); Resource[] resources = ((ResourcePatternResolver) ctx).getResources("classpath*:/META-INF/spring/conf*.xml");

Comments

Powered by Zendesk