It is not a recommended practise to have libraries placed in Tomcat’s lib directory to access classes in a web application. However, there are cases when you may want to flout this practise. Tomcat’s class loading mechanism will not allow you to do so since the web classes and the lib classes are loaded by different class loaders. The workaround in such a case is to use a custom bootstrap loader. This loader should be used to load all the application specific classes.
An example of a custom bootstrap loader is given below. Continue Reading
Tomcat creates the class-loaders with the parent-child hierarchy as shown in the diagram. The class loading is fairly intuitive. However a pragmatic developer needs to understand it properly to avoid problem with class instantiation since it differs a bit from the typical Java class loading mechanism.
Tomcat loads classes in the order shown below also described extensively in the Tomcat documentation. The quirk with the WebAppClassLoader is that it searches it’s local repositories first before delegating to the parent class loader, the exception being the JRE base classes.
If one does not want to bloat up the application wars by including all possible library jars, the standard way is to share the jars by putting them in Tomcat’s common lib directory so that they can be handled by the common loader rather than the web-app loader. To use a separate directory and to avoid cluttering common lib directory, one can enable the shared loader in conf/catalina.properties. Another alternative is to include the class path in Tomcat’s start-up class-path. Continue Reading