mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+255
-160
@@ -1,177 +1,272 @@
|
||||
---
|
||||
description: Comprehensive guidelines for effective Maven project management, covering code organization, dependency management, performance optimization, and security best practices. This rule provides actionable advice to avoid common pitfalls and promote maintainable, scalable Maven projects.
|
||||
globs: **/pom.xml
|
||||
description: This guide provides opinionated, actionable best practices for Maven projects, focusing on reproducible builds, efficient dependency management, and high code quality.
|
||||
globs: **/*.java
|
||||
---
|
||||
---
|
||||
- **Introduction**
|
||||
This guide provides comprehensive best practices for effectively using Maven in Java development, focusing on code organization, dependency management, performance, security, testing, and tooling. Adhering to these guidelines will result in more maintainable, scalable, and robust Maven projects.
|
||||
# Maven Best Practices
|
||||
|
||||
- **Code Organization and Structure**
|
||||
Maven is the definitive build tool for modern Java. Adhere to these rules for consistent, maintainable, and high-quality projects.
|
||||
|
||||
- **Standard Directory Structure:**
|
||||
- Follow the standard Maven directory structure for consistency and ease of understanding:
|
||||
|
||||
project-root/
|
||||
├── src/
|
||||
│ ├── main/
|
||||
│ │ ├── java/ # Source code
|
||||
│ │ ├── resources/ # Resources (e.g., properties files)
|
||||
│ ├── test/
|
||||
│ │ ├── java/ # Test code
|
||||
│ │ ├── resources/ # Test resources
|
||||
├── pom.xml # Maven project definition
|
||||
|
||||
- **File Naming Conventions:**
|
||||
- Java source files: `YourClass.java`
|
||||
- Resource files: `application.properties`, `log4j2.xml`
|
||||
- POM files: `pom.xml`
|
||||
- **Module Organization (Multi-Module Projects):**
|
||||
- For larger projects, consider using a multi-module structure:
|
||||
|
||||
parent-project/
|
||||
├── pom.xml # Parent POM (defines dependencies, plugins, versions)
|
||||
├── module1/
|
||||
│ └── pom.xml # Module-specific POM
|
||||
├── module2/
|
||||
│ └── pom.xml
|
||||
└── ...
|
||||
|
||||
- Parent POM handles shared configurations.
|
||||
- Each module has its specific functionality and dependencies.
|
||||
- **Component Architecture:**
|
||||
- Organize code into logical components (e.g., data access, business logic, UI).
|
||||
- Use interfaces to define contracts between components.
|
||||
- Employ dependency injection to manage component dependencies.
|
||||
- **Code Splitting Strategies:**
|
||||
- Split large classes into smaller, more manageable units based on functionality.
|
||||
- Create utility classes for reusable code.
|
||||
- Break down complex processes into separate methods.
|
||||
## Code Organization and Structure
|
||||
|
||||
- **Common Patterns and Anti-patterns**
|
||||
### Centralize Configuration with a Parent POM/BOM
|
||||
|
||||
- **Design Patterns:**
|
||||
- **Factory Pattern:** Use factories to create instances of objects, especially when the exact type of object needed is not known at compile time.
|
||||
- **Singleton Pattern:** Ensure only one instance of a class exists (use with caution).
|
||||
- **Strategy Pattern:** Define a family of algorithms, encapsulate each one, and make them interchangeable.
|
||||
- **Recommended Approaches:**
|
||||
- **Dependency Injection:** Use frameworks like Spring to manage dependencies and improve testability.
|
||||
- **Configuration Management:** Externalize configuration using properties files or environment variables.
|
||||
- **Logging:** Use a logging framework like Log4j 2 or SLF4J for consistent logging practices.
|
||||
- **Anti-Patterns:**
|
||||
- **God Classes:** Avoid large, monolithic classes that handle too many responsibilities.
|
||||
- **Copy-Paste Programming:** Extract common code into reusable methods or classes.
|
||||
- **Ignoring Exceptions:** Always handle exceptions properly; don't just catch and ignore them.
|
||||
- **Hardcoding Values:** Externalize configuration values to avoid hardcoding.
|
||||
- **State Management:**
|
||||
- For web applications, use session management carefully.
|
||||
- Avoid storing sensitive data in sessions.
|
||||
- Use appropriate scoping for managed beans (e.g., request, session, application).
|
||||
- **Error Handling:**
|
||||
- Use try-catch blocks to handle exceptions gracefully.
|
||||
- Log exceptions with sufficient context.
|
||||
- Provide user-friendly error messages.
|
||||
- Use custom exception classes to represent specific error conditions.
|
||||
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.
|
||||
|
||||
- **Performance Considerations**
|
||||
❌ 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>
|
||||
```
|
||||
|
||||
- **Optimization Techniques:**
|
||||
- **Profiling:** Use profiling tools (e.g., VisualVM, YourKit) to identify performance bottlenecks.
|
||||
- **Caching:** Implement caching (e.g., using Ehcache or Redis) to reduce database load and improve response times.
|
||||
- **Connection Pooling:** Use connection pooling to manage database connections efficiently.
|
||||
- **Efficient Data Structures:** Choose appropriate data structures for your specific needs (e.g., HashMap, ArrayList).
|
||||
- **Optimize Database Queries:** Use indexes, avoid full table scans, and optimize SQL queries.
|
||||
- **Memory Management:**
|
||||
- **Garbage Collection:** Understand how garbage collection works and tune JVM settings if necessary.
|
||||
- **Object Pooling:** Use object pooling for frequently created and destroyed objects.
|
||||
- **Avoid Memory Leaks:** Ensure resources are properly released to prevent memory leaks.
|
||||
- **Bundle Size Optimization:**
|
||||
- Use ProGuard or other code shrinking tools to reduce the size of JAR files.
|
||||
- Remove unused dependencies.
|
||||
- Optimize resource files (e.g., compress images).
|
||||
- **Lazy Loading:**
|
||||
- Use lazy loading for resources or data that are not immediately needed.
|
||||
- Implement pagination for large datasets.
|
||||
✅ GOOD: Define a parent POM with `<dependencyManagement>` and `<pluginManagement>`. Child modules inherit these.
|
||||
|
||||
- **Security Best Practices**
|
||||
```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>
|
||||
|
||||
- **Common Vulnerabilities:**
|
||||
- **Dependency Vulnerabilities:** Regularly scan dependencies for known vulnerabilities (using Snyk, OWASP Dependency-Check).
|
||||
- **SQL Injection:** Use parameterized queries or ORM frameworks to prevent SQL injection.
|
||||
- **Cross-Site Scripting (XSS):** Encode user input properly to prevent XSS attacks.
|
||||
- **Cross-Site Request Forgery (CSRF):** Implement CSRF protection mechanisms.
|
||||
- **Authentication and Authorization Flaws:** Use strong authentication and authorization mechanisms.
|
||||
- **Input Validation:**
|
||||
- Validate all user input to prevent malicious data from entering the system.
|
||||
- Use whitelisting to define allowed values.
|
||||
- Sanitize input to remove potentially harmful characters.
|
||||
- **Authentication and Authorization:**
|
||||
- Use a secure authentication mechanism (e.g., OAuth 2.0, OpenID Connect).
|
||||
- Implement role-based access control (RBAC) to restrict access to resources.
|
||||
- Use strong password policies.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use HTTPS to secure communication.
|
||||
- Store passwords securely using hashing algorithms (e.g., bcrypt).
|
||||
- **Secure API Communication:**
|
||||
- Use API keys or OAuth 2.0 to authenticate API requests.
|
||||
- Validate API requests to prevent malicious input.
|
||||
- Limit the rate of API requests to prevent abuse.
|
||||
<!-- 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>
|
||||
```
|
||||
|
||||
- **Testing Approaches**
|
||||
## Common Patterns and Anti-patterns
|
||||
|
||||
- **Unit Testing:**
|
||||
- Use JUnit or TestNG for unit testing.
|
||||
- Write tests for all critical components and methods.
|
||||
- Use mocking frameworks (e.g., Mockito, EasyMock) to isolate units under test.
|
||||
- Aim for high code coverage.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different components or services.
|
||||
- Use embedded databases or mock services for testing.
|
||||
- Test data access layers, API endpoints, and message queues.
|
||||
- **End-to-End Testing:**
|
||||
- Simulate real user scenarios to test the entire application flow.
|
||||
- Use testing frameworks like Selenium or Cypress.
|
||||
- Test the user interface, business logic, and data access layers.
|
||||
- **Test Organization:**
|
||||
- Place test code in the `src/test/java` directory.
|
||||
- Organize tests into packages that mirror the source code structure.
|
||||
- Use descriptive test names.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking frameworks to create mock objects for dependencies.
|
||||
- Use stubs to provide predefined responses for method calls.
|
||||
- Avoid over-mocking; test the actual behavior when possible.
|
||||
### Declare the Narrowest Possible Dependency Scope
|
||||
|
||||
- **Common Pitfalls and Gotchas**
|
||||
Limit dependency transitivity and classpath bloat by using the most restrictive scope (`compile`, `provided`, `runtime`, `test`).
|
||||
|
||||
- **Dependency Conflicts:** Use `mvn dependency:tree` to identify and resolve dependency conflicts. Use `<dependencyManagement>` to control versions.
|
||||
- **Version Mismatches:** Ensure all modules in a multi-module project use compatible versions of dependencies.
|
||||
- **Transitive Dependencies:** Be aware of transitive dependencies and their potential impact on your project.
|
||||
- **Incorrect Scopes:** Use the correct dependency scopes (e.g., compile, runtime, test, provided) to avoid including unnecessary dependencies in the final artifact.
|
||||
- **Snapshot Dependencies:** Avoid using snapshot dependencies in production environments.
|
||||
❌ 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>
|
||||
```
|
||||
|
||||
- **Tooling and Environment**
|
||||
✅ 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.
|
||||
|
||||
- **Recommended Development Tools:**
|
||||
- **IDE:** IntelliJ IDEA, Eclipse, NetBeans
|
||||
- **Build Tool:** Apache Maven
|
||||
- **Version Control:** Git
|
||||
- **Dependency Scanning:** Snyk, OWASP Dependency-Check
|
||||
- **Static Analysis:** SonarQube, FindBugs
|
||||
- **Build Configuration:**
|
||||
- Use properties to define reusable values (e.g., versions, file paths).
|
||||
- Configure plugins properly and use appropriate versions.
|
||||
- Use profiles to manage different build configurations (e.g., development, production).
|
||||
- **Linting and Formatting:**
|
||||
- Use code formatters (e.g., IntelliJ IDEA code style, Eclipse code formatter) to ensure consistent code formatting.
|
||||
- Use static analysis tools to identify potential issues.
|
||||
- **Deployment:**
|
||||
- Use Maven plugins (e.g., `maven-deploy-plugin`) to deploy artifacts to a repository.
|
||||
- Use configuration management tools (e.g., Ansible, Chef, Puppet) to automate deployment.
|
||||
- Follow best practices for deploying Java applications (e.g., using application servers, containers).
|
||||
- **CI/CD Integration:**
|
||||
- Integrate Maven builds with CI/CD pipelines (e.g., Jenkins, GitLab CI, GitHub Actions).
|
||||
- Automate testing, code analysis, and deployment.
|
||||
- Use build automation tools to manage the build process.
|
||||
```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>
|
||||
```
|
||||
|
||||
- **Conclusion**
|
||||
By adhering to these best practices, you can build robust, maintainable, and secure Maven projects. Regular code reviews, continuous integration, and proactive dependency management will further enhance the quality and reliability of your software.
|
||||
### 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>
|
||||
```
|
||||
Reference in New Issue
Block a user