Maven – Build Java Project Create Jar File And Run Java Application With External Library

Prerequisites

Development environment

  1. JDK 1.8 Downloads
  2. Eclipse Mars Download

Step 1 Create New Maven-based Dynamic Web Project

Step 1.1 Create New Java Project

  • Launch Eclipse IDE;
  • Go to File -> New -> Others… -> Java Project.
  • Click Next.
  • Choose any project name you want then click Finish.

Step 1.2 Convert The Project To Maven Project

Right click to the project; select Configure->Convert to Maven Project. Eclipse will generate Project Object Model (pom.xml) file. Open the file by Eclipse text editor then paste the content below.

Step 2 Create Java Class

Copy the code below to clipboard; Select src folder in your project; Press CTRL + V; Eclipse IDE will automatically create package & class file with the code that’s pasted from clipboard.

Step 3 Create log4j.properties

  • Right click to the project; select New->Folder and name it config
  • Create an empty file named log4j.properties under config folder
  • Paste the content below:

Step 4 Configure Maven Runtime Environment

  • Right click to the project; select Run As -> Run Configurations
  • Right click to Maven Build; select New
  • Click Browse Workspace…
  • Select the project then click Ok.
  • Select JRE tab
  • Click Installed JREs… button to add/remove or edit JRE definition.
  • Click Add button.
  • Select Standard VM; then click Next.
  • Click Directory button to select the root folder of JDK installation. Select the folder then click Ok.
  • Click Finish.
  • Check the JDK then click Ok.
  • CLick Apply.
  • Click Close.

Note: you can see some compilation errors in your code as in this example; I don’t configure build path for the project. So you still can build the project using maven without any problem.

Step 5 Build The Project With Maven

  • Right click to the project; select Run As -> Maven build…
  • Enter clean dependency:copy-dependencies process-resources package in goals field.
  • Click Run.

Console window output

Project and output folder structure

Step 5 Run The Application

Run the jar file

Output

Log information will be logged in Console window as well as the configured file in log4j.properties. In this example, it’s C:/log/test.log.