Section B.5. Loading Resources from the CLASSPATH

B.5. Loading Resources from the CLASSPATH

Both the SystemPropertiesUtil and Log4jConfigurator utilities use ResourceLoader to find resources (a property file and the Log4J configuration file) on the application CLASSPATH. The ResourceLoader utility looks like Example B-10.

Example B-10.
 package com.jbossatwork.util; import*; import*; import java.util.*; public class ResourceLoader {     /**      * Making the default (no arg) constructor private      * ensures that this class cannnot be instantiated.      */     private ResourceLoader(  ) {  }     public static Properties getAsProperties(String name) {         Properties props = new Properties(  );         URL url = ResourceLoader.getAsUrl(name);          if (url != null) {             try {                  // Load the properties using the URL (from the CLASSPATH).                  props.load(url.openStream(  ));             } catch (IOException e) {             }         }         return props;     }     public static URL getAsUrl(String name) {         ClassLoader classLoader = Thread.currentThread(  ).getContextClassLoader(  );         return classLoader.getResource(name);     } } 

The ResourceUtil.getAsProperties( ) method calls ResourceUtil.getAsUrl( ) to find a properties file as an URL on the application CLASSPATH. The props.load(url.openStream( )) call first opens the URL as an InputStream and then loads the properties file.

The ResourceUtil.getAsUrl( ) method uses the Thread Context ClassLoader to find a properties file as an URL on the CLASSPATH application. The call to Thread.currentThread( ).getContextClassLoader( ) gets the current Thread's ClassLoader, and the classLoader.getResource(propsFileName) call searches for a properties filename on the application CLASSPATH and returns a that points to a resource (a properties file, data file, .class file, and so on). The Thread Context ClassLoader is the ClassLoader used by the creator of the Thread that runs your code. By using the Thread Context ClassLoader, we're guaranteed to load the resource as long as it's on the application's CLASSPATH. For more information on deployment , please see Chapter 3. See Appendix A for more information on ClassLoaders.

Packaging properties files in a JAR is cleaner than using external property files that reside on a disk directory because the directory structure for your deployment environment could differ on each machine where you deploy your application. Using JAR files for packaging is a standard technique for both J2SE and J2EE applications.

We've shown all the components to use Apache Commons Logging and Log4J, but where do all the pieces belong?

JBoss at Work. A Practical Guide
JBoss at Work: A Practical Guide
ISBN: 0596007345
EAN: 2147483647
Year: 2004
Pages: 197

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: