Excuting code
Have main method
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
Run the compiled class
running with arguments that are passed to the main(), all args serparted by space
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
Run
mvn package
Uber/Fat jar - Have jar with dependencies
Add to pom.xml
Run
mvn package
Or use maven-assembly-plugin
Can also use shade plugin https://maven.apache.org/plugins/maven-shade-plugin/index.html
Run jar
Add to pom.xml
In command line run:
mvn exec:java
NOTE: The phase this is set is not specified, so should be run as pluging goal instead of using lifecylce ie mvn verify
Command line
creating jar
Add individually:
jar cvf <name of jar>.jar file1 file2 directory1 directoy2 ...
Add all, must be in directory
jar cvf <name of jar>.jar .
NOTE: v
in the flag is for verbose, and is optional
Running jar
java -jar helloworld.jar
Running main() method
java -cp jarName.jar <packageName.ClassName> <argumentsIfAny>
Use Docker
Create the jar as above, and check it working
Create a dockerfile
Run container
see project here https://github.com/hanfak/docker-java-maven-rapidoid this has notes on how to set it up. I have used the maven-assembly-plugin to create the jar. Where the docker file runs this jar.
Using maven fabric8
Last updated