AI Rules for Java

Guide for effective AI interaction patterns when working with Java code.

Java Rules

.cusor/rules/java.mdc

---
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, JUnit, 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);
    }
}