Java Cursor Rules: AI-Powered Development Best Practices

Cursor rules for Java development enforcing clean code standards, Spring Boot patterns, and best practices with AI assistance for production-ready applications.

January 15, 2024by PromptGenius Team
javacursor-rulesai-codingbest-practicesspring-boot

Overview

Professional cursor rules for Java development that enforce modern standards and best practices. These rules help AI assistants generate clean, secure, and maintainable Java code with proper context and documentation.

Note:

Enforces clean code principles, Spring Boot best practices, and context-aware code generation for production-ready development.

Rules Configuration

---
description: Enforces best practices for Java development, focusing on context-aware code generation, modern patterns, and maintainable architecture. Provides comprehensive guidelines for writing clean, efficient, and secure Java code with proper context.
globs: **/*.java
---
# Java Best Practices

You are an expert in Java programming, Spring Boot, Spring Framework, Maven, and related Java technologies.
You understand modern Java development practices, architectural patterns, and the importance of providing complete context in code generation.

### Context-Aware Code Generation
- Always provide complete class context including imports, package declarations, and necessary annotations
- Include relevant configuration files (application.properties/yaml) when generating Spring Boot applications
- Generate complete method signatures with proper parameter types, return types, and exceptions
- Include comprehensive Javadoc comments explaining the purpose, parameters, return values, and exceptions
- Provide context about the class's role in the larger system architecture

### Code Style and Structure
- Follow clean code principles with meaningful names and proper documentation
- Structure code in logical packages following domain-driven design principles
- Implement proper separation of concerns (controllers, services, repositories, models)
- Use modern Java features (records, sealed classes, pattern matching) appropriately
- Maintain consistent code formatting and style across the codebase

### Spring Boot Best Practices
- Use Spring Boot 3.x features and best practices
- Implement proper dependency injection using constructor injection
- Configure Spring Security with modern authentication methods
- Use Spring Data JPA with proper entity relationships
- Implement proper exception handling with @ControllerAdvice
- Configure proper logging and monitoring

### Testing and Quality
- Write comprehensive unit tests with proper test context
- Include integration tests for critical paths
- Use proper mocking strategies with Mockito
- Implement test containers for database testing
- Include performance tests for critical components
- Maintain high test coverage for core business logic

### Security and Performance
- Implement proper input validation and sanitization
- Use secure password hashing and token management
- Configure proper CORS and CSRF protection
- Implement rate limiting and request validation
- Use proper caching strategies
- Optimize database queries and indexes

### API Design
- Follow RESTful principles with proper HTTP methods
- Use proper status codes and error responses
- Implement proper versioning strategies
- Document APIs using OpenAPI/Swagger
- Include proper request/response validation
- Implement proper pagination and filtering

### Database and Data Access
- Use proper JPA entity relationships
- Implement proper transaction management
- Use database migrations (Flyway/Liquibase)
- Optimize queries and use proper indexing
- Implement proper connection pooling
- Use proper database isolation levels

### Build and Deployment
- Use Maven/Gradle with proper dependency management
- Implement proper CI/CD pipelines
- Use Docker for containerization
- Configure proper environment variables
- Implement proper logging and monitoring
- Use proper deployment strategies

### Examples

```java
/**
 * UserRepository handles database operations for User entities.
 * Provides methods for CRUD operations and custom queries.
 */
@Repository
@Transactional(readOnly = true)
public class UserRepository {
    private final UserMapper mapper;
    private final EntityManager entityManager;

    @Autowired
    public UserRepository(UserMapper mapper, EntityManager entityManager) {
        this.mapper = mapper;
        this.entityManager = entityManager;
    }

    /**
     * Finds a user by their email address.
     *
     * @param email The email address to search for
     * @return Optional containing the user if found
     * @throws DataAccessException if database access fails
     */
    public Optional<User> findByEmail(String email) {
        try {
            return Optional.ofNullable(mapper.findByEmail(email));
        } catch (Exception e) {
            throw new DataAccessException("Failed to find user by email", e);
        }
    }
}

/**
 * Tests for UserRepository functionality.
 */
@SpringBootTest
@AutoConfigureTestDatabase
class UserRepositoryTest {
    @MockBean
    private UserMapper mapper;

    @Autowired
    private UserRepository repository;

    @Test
    @DisplayName("Should find user by email when user exists")
    void shouldFindUserByEmail() {
        // Given
        String email = "[email protected]";
        User user = new User(email);
        when(mapper.findByEmail(email)).thenReturn(user);

        // When
        Optional<User> result = repository.findByEmail(email);

        // Then
        assertTrue(result.isPresent());
        assertEquals(email, result.get().getEmail());
        verify(mapper).findByEmail(email);
    }

    @Test
    @DisplayName("Should return empty optional when user not found")
    void shouldReturnEmptyWhenUserNotFound() {
        // Given
        String email = "[email protected]";
        when(mapper.findByEmail(email)).thenReturn(null);

        // When
        Optional<User> result = repository.findByEmail(email);

        // Then
        assertTrue(result.isEmpty());
        verify(mapper).findByEmail(email);
    }
}

Key Features

📦

Complete Code Context

Full package declarations, imports, and Javadoc included automatically

🚀

Spring Boot Optimized

Modern Spring Boot 3.x patterns and best practices built-in

Testing Built-In

Automatic generation of JUnit 5 tests with proper mocking

🔒

Security First

Input validation, Spring Security integration, and secure patterns

📐

Clean Architecture

Separation of concerns with controllers, services, and repositories

🏗️

Enterprise Ready

JPA entities, transaction management, and database migrations

Installation

1

Choose Your IDE

Select the appropriate file path based on your development environment.

2

Create the Rules File

Create the cursor rules file in your project:

Create file: .cursor/rules/java.mdc

3

Add the Rules Configuration

Copy the rules configuration below into your newly created file.

4

Start Coding

Your AI assistant will now follow Java best practices automatically.

Use Cases

Web Applications

Full-stack Spring Boot applications with modern patterns and proper architecture

API Development

RESTful APIs with proper versioning, validation, and OpenAPI documentation

Microservices

Containerized Java services with clean boundaries and comprehensive testing

Enterprise Systems

Large-scale applications with proper transaction management and security

Standards Reference

StandardDescriptionEnforcement
Clean CodeMeaningful names, small methods, proper documentationEnforced via structure
Type SafetyStrict type hints and return typesRequired for all methods
JavadocComprehensive documentation blocksRequired for classes and methods
TestingJUnit 5 with Mockito test coverageAuto-generated with code
SecurityInput validation and Spring SecurityBuilt into patterns
ArchitectureClean separation of concernsEnforced via structure

Note:

Combine these rules with Maven/Gradle build checks and SonarQube for maximum code quality enforcement.

Best Practices

Code Organization

  • Controllers handle HTTP requests only
  • Services contain business logic
  • Repositories manage data access
  • Entities represent domain objects

Type Safety

  • Always use type hints for parameters
  • Always declare return types explicitly
  • Use generics appropriately
  • Leverage Java records for immutable data

Testing Strategy

  • Unit tests for business logic
  • Integration tests for database operations
  • API tests for endpoint functionality
  • Proper mocking for external dependencies

Note:

These rules work with any Java project but are optimized for Spring Boot applications. Adjust framework-specific sections as needed for other frameworks.

Explore related cursor rules for complementary technologies and frameworks: