How to put an external file in the classpath

This article describes how to include an external properties file in the classpath of an application that has been deployed into versions of JBossAS 7.0 and newer.

 

It should be noted that providing application configuration in this way is not a best practice as it does not get automatically propogated to the nodes in a cluster.

 

JBoss AS 7.x makes use of the new JBoss Modules framework:

JBoss Modules is a standalone implementation of a modular (non-hierarchical) class loading and execution environment for Java. In other words, rather than a single class loader which loads all JARs into a flat class path, each library becomes a module which only links against the exact modules it depends on, and nothing more. It implements a thread-safe, fast, and highly concurrent delegating class loader model, coupled to an extensible module resolution system, which combine to form a unique, simple and powerful system for application execution and distribution.

The secret to getting external files into your application's classpath is to make use of the module classloader.

 

1. Create a new module for your configuration files

 

jboss-as-7/modules/com/yourcompany/configuration/main/module.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mycompany.settings">
    <resources>
        <resource-root path="."/>
    </resources>
</module>

 

 

2. Add your properties files to the module

 

jboss-as-7/
   modules/
      com/
         yourcompany/
            configuration/
               main/
                 module.xml
                 settings.properties
                 other-settings.xml

 

 

3. Add your module to your application classpath in a jboss-deployment-structure.xml file
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
  <deployment>
    <dependencies>
      <module name="com.mycompany.settings" />
    </dependencies>
  </deployment>
</jboss-deployment-structure>

 

 

This file must be placed either in the META-INF directory of your EAR file or the WEB-INF directory of your WAR file. See Class Loading in AS7 for more information.

4. OR add your module to your application classpath using a MANIFEST.MF entry

 

Manifest-Version: 1.0
Dependencies: com.mycompany.settings

 

 

5. Load a properties file from the classloader in your application

 

InputStream settingsStream = this.getClass().getClassLoader().getResourceAsStream("settings.properties");