To run a Java app a main() method must be supplied. This is where all the code is wired up (objects newed up) and methods run. It is the entry point of a Java app.
Use command line for single class
This way is best for single file apps (which is rare). If using an IDE then these steps are very easy and wont really ever need to use the command line. Must have a main method in the class.
NOTE: make sure the path for the jdk is setup
compile the class
javac Helloworld.class
Run the compiled class
java Helloworld
running with arguments that are passed to the main(), all args serparted by space
java Helloworld arg1 arg2 arg3
Use intellij
In class with main, click on the green arrow next to the main() method on the left hand side.
Use jar
Manifest file
A manifest file is created when a jar is created. It contains info about the files that packaged in the jar
Add entry point for running jar
In manifest file, add Main-Class: <MyPackage.MyClass>. Then run the jar.
NOTE: Always have empty line or carriage return on last line
using maven
Always good to have
Build jar
Simple jar
Add to pom.xml
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!-- DO NOT include log4j.properties file in your Jar -->
<excludes>
<exclude>**/log4j.properties</exclude>
</excludes>
<archive>
<manifest>
<!-- Jar file entry point, where main method is-->
<mainClass>com.hanfak.wiring.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
Run mvn package
Uber/Fat jar - Have jar with dependencies
Add to pom.xml
<build>
<plugins>
...
<!-- Make this jar executable -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/log4j.properties</exclude>
</excludes>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.hanfak.wiring.App</mainClass>
<classpathPrefix>dependency-jars/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<!-- Copy project dependency -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<!-- exclude junit, we need runtime dependency only -->
<includeScope>runtime</includeScope>
<outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>