Java – add spring jar to class path

javanetbeans

I have a netbeans java console project which uses Spring 3.0 ( which is a bunch of jars instead of a single jar).

when i try to execute it from the command line i get

 Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: com.aosprojects.transportservice.runner.InitialRunner. Program will exit.

How to fix this?

I have tried using -cp to specify the folder with all the jars in it like

java -cp libs/spring/* -jar dist/XXXXX.jar

Best Answer

If you're using maven to build your application, it runs in the netbeans IDE, but you'll need to define a plugin in your maven pom.xml in order to include all of the required .jars in your final .jar to make it executable.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>yourmainpackagename.YourMainClass</mainClass>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                    </transformers>
                </configuration>
            </execution>
        </executions>
    </plugin>

This approach uses the maven shade plugin. You could also be using the maven assembly plugin, be prepared to face nasty bugs though :p

cheers.

Related Topic