К основному содержанию
правило

maven — правило для Cursor: что делает и как установить

Правило настраивает Cursor для проектов на Maven: помогает выносить зависимости в родительский POM и изолировать их через строгие scope.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/maven.mdc
Открыть на GitHub

Что делает maven

Правило активируется для файлов **/*.java и задаёт стандарты проектирования pom.xml. Ассистент перестаёт дублировать версии в дочерних модулях. Общие библиотеки и плагины переносятся в секции <dependencyManagement> и <pluginManagement> родительского POM или BOM.

Инструкция требует явно задавать минимальный scope (compile, provided, runtime, test), чтобы не засорять classpath приложения тестовыми пакетами. Конфликтующие транзитивные зависимости отсекаются через тег <exclusions>, а для сборки предписывается использовать скрипт ./mvnw вместо системного mvn.

Настройки окружения правило требует выносить в переменные среды, а не прятать внутри профилей сборки.

Какие задачи решает

  • вынести версии зависимостей в родительский <dependencyManagement>
  • изолировать тестовые библиотеки явным указанием scope test
  • исключить конфликтующие транзитивные пакеты через <exclusions>
  • зафиксировать версию сборщика с помощью Maven Wrapper (./mvnw)

Примеры запросов агенту

  • Сконфигурируй родительский pom.xml с блоком dependencyManagement для модулей
  • Добавь зависимость JUnit 5 с подходящим тестовым scope в pom.xml
  • Исключи конфликтующую транзитивную зависимость из подключаемой библиотеки

Как установить maven

Вручную: положить файлы

.cursor/rules/maven.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о maven

Как установить maven в Cursor?

Сохраните файл правила по пути .cursor/rules/maven.mdc в корне вашего проекта.

Что делает правило maven?

Оно обучает ИИ-ассистента лучшим практикам Maven: централизации версий в родительском POM, сужению scope зависимостей и исключению транзитивных конфликтов.

Зачем правило требует использовать Maven Wrapper?

Команда mvn wrapper:wrapper фиксирует версию сборщика прямо в репозитории. Запуск через ./mvnw исключает сбои из-за несовпадения версий Maven у разных разработчиков.

Исходный текст

maven.mdc · CC0-1.0
---
description: This guide provides opinionated, actionable best practices for Maven projects, focusing on reproducible builds, efficient dependency management, and high code quality.
globs: **/*.java
---
# Maven Best Practices

Maven is the definitive build tool for modern Java. Adhere to these rules for consistent, maintainable, and high-quality projects.

## Code Organization and Structure

### Centralize Configuration with a Parent POM/BOM

Always use a parent POM (or Bill of Materials - BOM) to define shared properties, plugin versions, and a `<dependencyManagement>` section. This guarantees consistent library versions and build behavior across all modules.

❌ BAD: Duplicating dependency versions and plugin configurations in every child `pom.xml`.
```xml
<!-- child-module/pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>3.2.0</version> <!-- Hardcoded, duplicated -->
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.11.0</version> <!-- Hardcoded, duplicated -->
            <configuration><release>17</release></configuration>
        </plugin>
    </plugins>
</build>
```

✅ GOOD: Define a parent POM with `<dependencyManagement>` and `<pluginManagement>`. Child modules inherit these.

```xml
<!-- parent/pom.xml -->
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>my-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <java.version>17</java.version>
        <spring-boot.version>3.2.0</spring-boot.version>
        <maven.compiler.plugin.version>3.11.0</maven.compiler.plugin.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.compiler.plugin.version}</version>
                    <configuration><release>${java.version}</release></configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

<!-- child-module/pom.xml -->
<project>
    <parent>
        <groupId>com.mycompany</groupId>
        <artifactId>my-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>my-child-module</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Version inherited from parent's dependencyManagement -->
        </dependency>
    </dependencies>
</project>
```

## Common Patterns and Anti-patterns

### Declare the Narrowest Possible Dependency Scope

Limit dependency transitivity and classpath bloat by using the most restrictive scope (`compile`, `provided`, `runtime`, `test`).

❌ BAD: Using `compile` scope for everything, including test-only dependencies.
```xml
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.11.0</version>
    <!-- Missing scope, defaults to compile -->
</dependency>
```

✅ GOOD: Explicitly define scopes.
*   `compile` (default): Available in all classpaths, propagated to dependents. For core libraries.
*   `provided`: Expected to be provided by JDK or container at runtime. For Servlet API, Java EE APIs.
*   `runtime`: Not needed for compilation, but for execution. For JDBC drivers.
*   `test`: Only for test compilation and execution. For JUnit, Mockito.

```xml
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <scope>test</scope> <!-- Correct scope for testing -->
    </dependency>
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.0.0</version>
        <scope>provided</scope> <!-- Provided by web container -->
    </dependency>
</dependencies>
```

### Manage Transitive Dependencies with Exclusions

Prevent unwanted or conflicting transitive dependencies from polluting your classpath.

❌ BAD: Relying on Maven's "nearest definition" for conflicting transitive dependencies, leading to unpredictable builds or runtime issues.
```xml
<!-- Project A depends on B (which depends on D 1.0) and C (which depends on D 2.0) -->
<!-- Maven might pick D 1.0 or D 2.0 based on declaration order/depth -->
<dependency>
    <groupId>com.example</groupId>
    <artifactId>library-b</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.example</groupId>
    <artifactId>library-c</artifactId>
    <version>1.0</version>
</dependency>
```

✅ GOOD: Explicitly exclude problematic transitive dependencies and declare the desired version directly.

```xml
<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>library-b</artifactId>
        <version>1.0</version>
        <exclusions>
            <exclusion>
                <groupId>com.example</groupId>
                <artifactId>dependency-d</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>library-c</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>dependency-d</artifactId>
        <version>2.0</version> <!-- Explicitly declare the desired version -->
    </dependency>
</dependencies>
```

## Performance Considerations

### Use Maven Wrapper for Consistent Builds

Ensure all developers and CI/CD pipelines use the exact same Maven version, preventing "works on my machine" issues related to Maven itself.

✅ GOOD: Include Maven Wrapper in your project.
```bash
mvn wrapper:wrapper
```
Then, use `./mvnw` (or `mvnw.cmd` on Windows) instead of `mvn`.
```bash
./mvnw clean install
```

## Common Pitfalls and Gotchas

### Avoid Over-reliance on Maven Profiles for Environment Configuration

Modern applications should be environment-agnostic (12-factor app principles). Use external configuration (environment variables, configuration servers) for environment-specific settings, not Maven profiles.

❌ BAD: Using profiles to inject environment-specific database URLs or API keys.
```xml
<!-- profile in pom.xml -->
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <db.url>jdbc:h2:mem:devdb</db.url>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <db.url>jdbc:postgresql://prod-db:5432/appdb</db.url>
        </properties>
    </profile>
</profiles>
```

✅ GOOD: Keep application configuration external to the build. Maven profiles are acceptable for *build process* variations (e.g., different test suites, packaging types), but not runtime environment configuration.

## Testing Approaches

### Integrate Static Analysis Plugins

Enforce coding standards and identify potential issues early by integrating static analysis tools like Checkstyle, SpotBugs, or PMD into the Maven build lifecycle (e.g., `verify` phase).

✅ GOOD: Configure static analysis plugins in your parent POM's `<build>` section.

```xml
<!-- parent/pom.xml -->
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>3.3.1</version>
                <executions>
                    <execution>
                        <id>validate</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <configLocation>checkstyle.xml</configLocation>
                            <failsOnError>true</failsOnError>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.spotbugs</groupId>
                <artifactId>spotbugs-maven-plugin</artifactId>
                <version>4.8.3.0</version>
                <executions>
                    <execution>
                        <id>analyze</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
```

© sanjeed5 · CC0-1.0 · sanjeed5/awesome-cursor-rules-mdc

Похожие правила IDE

Все правила IDE по теме «Бэкенд и API» →
113-java-maven-documentation Juan Antonio Breña Moral Скилл формирует файл DEVELOPER.md для проектов на Maven. Он собирает цели плагинов и профили сборки прямо из структуры pom.xml. CX Codex +1 348установок java-maven pluginagentmarketplace Помогает настраивать pom.xml и управлять зависимостями через BOM в проектах на Apache Maven. CX Codex +1 894установок 110-java-maven-best-practices Juan Antonio Breña Moral Проверяет и переписывает Maven-конфигурацию по отраслевым практикам: зависимости через BOM, централизация версий, мультимодульные сборки. CX Codex +1 478установок maven-tools-mcp arvindand Сервер проверяет JVM-зависимости по данным Maven Central: ищет версии, оценивает состояние библиотек и предлагает обновления. Пригодится для аудита проекта и планирования правок в pom.xml. CX Codex +1 ★ 35звёзд репо graal oracle Помогает собирать и настраивать бинарники через GraalVM Native Image. Пригодится при отладке сборок, поиске проблем с рефлексией и настройке Gradle или Maven. CX Codex +1 375установок java-development официальный github Направляет разработку на чистой Java без фреймворков: согласует фичи с версией JDK, запускает сборку через Maven или Gradle и следит за зависимостями. 3установок

Из того же набора240

Весь набор →
mobx Правило для Cursor задаёт структуру MobX-приложения на React: единый RootStore, явные observables и observer только на листовых компонентах. ★ 3 580звёзд репо mlx Направляет Cursor при разработке ML-проектов на Apple Silicon: помогает писать модульный код на MLX, правильно компилировать шаги обучения и избегать ошибок с памятью. ★ 3 580звёзд репо mkdocs Задаёт правила для Markdown-документации в проектах MkDocs с темой Material. Пригодится, если хотите упорядочить навигацию и проверять страницы перед сборкой. ★ 3 580звёзд репо microsoft-teams Правило для Cursor с набором практик разработки приложений Microsoft Teams: структура проекта, Fluent UI, Adaptive Cards и Microsoft Graph. ★ 3 580звёзд репо matplotlib Правило задаёт практики для кода на matplotlib в файлах Python: объектный API, типы, сохранение графиков и контроль памяти. ★ 3 580звёзд репо material-ui Правило задаёт Cursor единый стиль работы с Material-UI: структура папок, тема, стили и компоненты. Пригодится, если проект на React с MUI растёт и хочется одинаковых решений. ★ 3 580звёзд репо llvm Настраивает Cursor на стандарты кодовой базы LLVM. Заставляет агента использовать структуры ADT, макросы LLVM_DEBUG и тесты LIT. ★ 3 580звёзд репо llamaindex-js Правило задаёт структуру приложений на llamaindex-js: от загрузки документов до запросов к индексу и запуска агентов. Пригодится, если Cursor пишет или меняет такой код. ★ 3 580звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой