Pages

Simple Maven Eclipse Project

What I'm about to do here is creating a simple desktop app using Apache Maven as build automation tool.

To follow me, ensure you have on your machine:
  1. Java JDK - I use version 11, the currently latest available LTS, but the app is so simple that virtually any JDK will do
  2. Eclipse IDE - Actually, on my machine I have Spring Tool Suite (STS) 4.6, but again, the job is so basic, that almost any Eclipse-based IDE would be alright

From Eclipse, I select the "Maven Project" wizard from "File | New | Project ...", there I go for creating a simple project, skipping archetype selection. Then I have to specify a group and artifact id for my stuff. I enter "dd" as group id and "simple" as artifact id.

The other fields have a good default - so I keep them as suggested and I just push the "Finish" button.

Since I used a very minimal approach, I'm not surprised by the warning in my project. I go straight to my pom.xml to complete it.

I want to set the character set used in my source code, using UTF-8 (strictly not a necessity, still a good idea), and, most importantly, I want to set both the source and target compiler to JDK 11.
I do that specifying these properties inside the project element:
<properties>
    <project.build.sourceEncoding>
        UTF-8
    </project.build.sourceEncoding>
    <maven.compiler.source>
        11
    </maven.compiler.source>
    <maven.compiler.target>
        11
    </maven.compiler.target>
</properties>
Here you can see the full pom.xml.

Theoretically, Eclipse should trigger a project rebuild as you save a change in the Maven configuration file. Unfortunately, this is not what often happens. However, you could force the job by pushing Alt-F5, or right-clicking on the project name in the Project Explorer, then select Maven | Update Project...

I add a plain vanilla class, simple.Main, with a main function to perform the usual hello job and I have the first version of my application.

Now I'd like to use maven to generate my app jar. To do that, I have to specify which goals my maven build target should achieve. I right click on the project folder in the Eclipse Package Explorer, then in the Run as menu I select the "Maven build ..." item. As goals I specify "clean package", meaning that I want to clean everything up, so to recompile all source files and then package them in a jar file.

Now I can run this target. In the console window I see the feedback from Maven until I get the final result, a jar, named in my case simple-0.0.1-SNAPSHOT.jar, has been put in the project target directory.

To see if it works as I expect, I open a shell, go to the target directory, and there I execute the jar:
java -cp simple-0.0.1-SNAPSHOT.jar simple.Main
I'm happy to get back the expected hello message, so I put the project on Github.

No comments:

Post a Comment