Каталог target в Java сборках: конфигурация и доступ из кода
Каталог target в конфигурации сборки Java
В Maven и Gradle target обозначает каталог результатов сборки: классы, тестовые классы, артефакты, отчеты. Путь к нему зависит от инструмента и настроек проекта.
Основной способ: свойство project.build.directory в Maven
В Maven путь к target задается в POM через элемент build/directory. По умолчанию это ${project.basedir}/target. Это значение доступно плагинам как ${project.build.directory}. Для Java кода его можно передать как системное свойство через maven-surefire-plugin.
<project ...>
<build>
<directory>${project.basedir}/target</directory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<systemPropertyVariables>
<target.dir>${project.build.directory}</target.dir>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
Java path target (путь к target в java)
Java класс читает путь:
import java.nio.file.Path;
import java.nio.file.Paths;
public class TargetPathDemo {
public static void main(String[] args) {
String raw = System.getProperty("target.dir", "target");
Path target = Paths.get(raw).toAbsolutePath().normalize();
System.out.println(target);
}
}
/home/user/project/target
Пример запуска:
mvn -q test
mvn -q exec:java -Dexec.mainClass=TargetPathDemo -Dtarget.dir="${PWD}/target"
Типичная ошибка: ожидание, что ${project.build.directory} доступно в Java автоматически. Maven не передает это свойство в JVM без настройки surefire, exec или другого плагина. Второй случай: путь содержит пробелы, и код сравнивает строки без нормализации. Решение: использовать Path, toAbsolutePath и normalize, а в POM передавать значение через systemPropertyVariables.
Как изменить каталог target на другой путь в Maven?
Цель: разместить результаты сборки вне стандартного каталога, например в build/out.
<build>
<directory>${project.basedir}/build/out</directory>
</build>
Проверка:
mvn clean package
ls build/out
classes test-classes maven-archiver my-app-1.0.jar
Некоторые плагины имеют собственные параметры outputDirectory и могут не учитывать build/directory. Например, maven-jar-plugin использует ${project.build.directory} по умолчанию. Если путь переопределен, стоит проверить конфигурацию плагинов. Также относительный путь в directory задается от basedir проекта, а не от текущего каталога запуска Maven.
Как получить путь к target в Java без плагинов сборки?
Вариант подходит для локального запуска или простых утилит, когда проект запускается из корня.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class LocalTargetPath {
public static void main(String[] args) throws Exception {
Path target = Paths.get("target").toAbsolutePath().normalize();
System.out.println("target exists: " + Files.exists(target));
System.out.println(target);
}
}
target exists: true /home/user/project/target
Если приложение запускается из другого каталога, путь будет указывать на target рядом с рабочим каталогом процесса. Это поведение зависит от user.dir:
java -Duser.dir=/opt/app -cp build/out/classes LocalTargetPath
target exists: false /opt/app/target
Ошибка возникает при запуске из IDE: рабочий каталог может быть корнем проекта или каталогом модуля. В многомодульном Maven проекте target каждого модуля отдельный. Решение: передавать абсолютный путь явно или читать свойство, сформированное сборкой.
Как настроить путь к build каталогу в Gradle?
В Gradle 7 и 8 используется layout.buildDirectory. Старый buildDir считается устаревшим.
// build.gradle.kts
layout.buildDirectory.set(file("build/out"))
// или для подкаталога target:
layout.buildDirectory.set(file("target"))
Получение пути в задаче:
tasks.register("printTarget") {
doLast {
println(layout.buildDirectory.get().asFile.absolutePath)
}
}
gradle printTarget
/home/user/project/target
В старых сборках используется buildDir = file("target"), но при обновлении Gradle это может вызвать предупреждение. Для Kotlin DSL стоит применять layout.buildDirectory. В Java коде Gradle не передает путь автоматически. Решение: добавить системное свойство в задачу JavaExec или Test.
Как передать путь target в тесты JUnit?
В Maven Surefire можно использовать systemPropertyVariables или argLine. В Gradle Test есть systemProperty.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<target.dir>${project.build.directory}</target.dir>
</systemPropertyVariables>
</configuration>
</plugin>
// build.gradle.kts
tasks.test {
systemProperty("target.dir", layout.buildDirectory.get().asFile.absolutePath)
}
Тест:
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TargetPathTest {
@Test
void targetPathIsAvailable() {
String raw = System.getProperty("target.dir");
Path target = Path.of(raw).toAbsolutePath().normalize();
assertTrue(target.endsWith("target"));
}
}
BUILD SUCCESS
Если свойство не задано, System.getProperty возвращает null. Path.of(null) выбрасывает NullPointerException. Решение: задавать значение по умолчанию, например Path.of(System.getProperty("target.dir", "target")). В Gradle путь нужно вычислять во время конфигурации или выполнения, а не в статическом поле теста.
Расширенные примеры работы с target path
Генерация properties файла с путем target через Maven ресурсы
Фильтрация ресурсов позволяет записать путь target в properties файл во время сборки.
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
src/main/resources/build-info.properties:
target.dir=${project.build.directory}
project.version=${project.version}
Java:
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Properties;
public class BuildInfoReader {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try (InputStream in = BuildInfoReader.class.getResourceAsStream("/build-info.properties")) {
props.load(in);
}
Path target = Path.of(props.getProperty("target.dir")).toAbsolutePath().normalize();
System.out.println(target);
}
}
/home/user/project/target
Проблема: filtering может ломать бинарные файлы. Решение: включать filtering только для текстовых ресурсов или использовать отдельный resource с include.
Вывод пути через maven-antrun-plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>validate</phase>
<goals><goal>run</goal></goals>
<configuration>
<target>
<echo message="Target path: ${project.build.directory}" />
</target>
</configuration>
</execution>
</executions>
</plugin>
mvn validate
[INFO] --- antrun:3.1.0:run (default) @ demo ---
[echo] Target path: /home/user/project/target
JavaExec в Gradle с передачей buildDirectory
// build.gradle.kts
plugins {
application
}
application {
mainClass.set("demo.Main")
}
tasks.named<JavaExec>("run") {
systemProperty("target.dir", layout.buildDirectory.get().asFile.absolutePath)
}
package demo;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
Path target = Path.of(System.getProperty("target.dir", "target"));
System.out.println("Build directory: " + target.toAbsolutePath().normalize());
}
}
./gradlew run
Build directory: /home/user/project/build
Определение target через classpath
Если классы загружены из target/classes, можно найти корень target через CodeSource.
import java.nio.file.Path;
import java.security.CodeSource;
public class ClasspathTarget {
public static void main(String[] args) throws Exception {
CodeSource source = ClasspathTarget.class.getProtectionDomain().getCodeSource();
Path classesDir = Path.of(source.getLocation().toURI());
Path target = classesDir.getParent();
System.out.println("Classes: " + classesDir);
System.out.println("Target: " + target);
}
}
Classes: /home/user/project/target/classes Target: /home/user/project/target
Ограничение: при упаковке в JAR путь указывает на JAR, а не на target. Метод подходит для тестов и локального запуска из классов.
Поиск target в многомодульном Maven проекте
<project>
<modules>
<module>core</module>
<module>web</module>
</modules>
</project>
В модуле core свойство ${project.build.directory} указывает на core/target, в модуле web на web/target. Для агрегатора можно использовать ${maven.multiModuleProjectDirectory}.
<systemPropertyVariables>
<target.dir>${project.build.directory}</target.dir>
<root.dir>${maven.multiModuleProjectDirectory}</root.dir>
</systemPropertyVariables>
Java:
Path moduleTarget = Path.of(System.getProperty("target.dir"));
Path root = Path.of(System.getProperty("root.dir"));
System.out.println("Module target: " + moduleTarget);
System.out.println("Project root: " + root);
System.out.println("Relative from root: " + root.relativize(moduleTarget));
Module target: /home/user/project/web/target Project root: /home/user/project Relative from root: web/target
Нормализация и проверка пути target
import java.nio.file.Files;
import java.nio.file.Path;
public class TargetValidator {
public static void main(String[] args) {
Path target = Path.of(System.getProperty("target.dir", "target"))
.toAbsolutePath()
.normalize();
if (!Files.exists(target)) {
System.out.println("Target directory does not exist yet: " + target);
return;
}
System.out.println("Real path: " + target.toRealPath());
System.out.println("Is directory: " + Files.isDirectory(target));
}
}
Real path: /home/user/project/target Is directory: true
Метод toRealPath требует существования пути. Для еще не созданного каталога применяется normalize.
Использование target в Maven exec plugin
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<mainClass>demo.Main</mainClass>
<systemProperties>
<systemProperty>
<key>target.dir</key>
<value>${project.build.directory}</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
mvn compile exec:java
Build directory: /home/user/project/target
Проверка target в CI
#!/usr/bin/env bash
set -euo pipefail
mvn -B clean verify
TARGET_DIR="${PWD}/target"
test -d "$TARGET_DIR"
find "$TARGET_DIR" -maxdepth 2 -type d | sort
/home/runner/work/project/target /home/runner/work/project/target/classes /home/runner/work/project/target/test-classes /home/runner/work/project/target/surefire-reports
Такой скрипт проверяет, что сборка создала ожидаемый каталог. Если каталог переопределен в POM, скрипт стоит синхронизировать с build/directory.