Sub topic 3
The Standard Java Project Layout
In the last chapter you compiled a class by hand. You had to tell javac exactly where the source file was and where to put the output. Both Maven and Gradle skip that step by expecting files in fixed places. This shared set of folders is called the standard directory layout. A directory layout is the way folders are arranged inside a project.
Why a Fixed Layout Helps
A build tool needs to know where your code lives. You could list every folder in a config file, but that takes work and invites mistakes. Maven and Gradle use convention over configuration instead. That means the tool follows a default rule unless you tell it otherwise. If your files sit in the expected folders, you write almost no setup.
The layout also helps people. Any Java developer can open a Maven or Gradle project and find the code right away.
The Folders
| Folder | What goes in it |
|---|---|
| `src/main/java` | Your application's Java source files |
| `src/main/resources` | Non-code files the app needs, such as config files |
| `src/test/java` | Java source files for tests |
| `src/test/resources` | Non-code files used only by tests |
Code in src/main ends up in the final JAR file. Code in src/test is compiled and run during testing, but it is left out of the JAR.
Packages Become Folders
A package is a named group of Java classes, such as com.example. Java expects each part of the package name to be a folder. So a class in package com.example goes in com/example/ under the java folder.
This tutorial's sample class starts with package com.example;, so its full path is:
src/main/java/com/example/App.javaIts test lives in the same package, but under the test folder:
src/test/java/com/example/AppTest.javaKeeping the same package in both places lets the test call methods that are not public, such as App.greeting.
Create the Layout Yourself
Run these commands in an empty folder to build the skeleton:
mkdir -p hello/src/main/java/com/example
mkdir -p hello/src/main/resources
mkdir -p hello/src/test/java/com/example
mkdir -p hello/src/test/resources
cd hello
find . -type dThe find command lists every folder so you can check the result.
Where the Output Goes
Build tools write compiled classes and JAR files to a separate output folder. Maven uses target/. Gradle uses build/. Both folders are created for you, and you can delete them at any time. Never put your own files there.
Exercise
You write a class OrderService in package com.shop.orders. Where should the file go, and where should its test OrderServiceTest go?
Show answer
The class goes in src/main/java/com/shop/orders/OrderService.java. The test goes in src/test/java/com/shop/orders/OrderServiceTest.java.
Exercise
Your app reads a file called settings.properties at runtime. Which folder should hold it?
Show answer
src/main/resources, because the running application needs it and it is not Java code.