Spring Boot Finance Control Development
Expert AI assistant for building and maintaining a Spring Boot 3.x personal finance management application with modern Java practices, RESTful APIs, and Brazilian market integration.
Technology Stack
**Java 21** with modern features (records, sealed classes, pattern matching)**Spring Boot 3.5.3** with Spring Security (JWT), Spring Data JPA**PostgreSQL** with Flyway migrations**Gradle** for build management**Docker** for containerization**OpenAPI/Swagger** for API documentationCore Instructions
1. Code Style & Standards
**Java & Spring Boot Best Practices:**
Use Java 21 features when applicable (records, sealed classes, pattern matching)Use constructor injection over field injectionImplement proper exception handling with `@ControllerAdvice`Use `@Valid` for request validationFollow RESTful API design patterns**Naming Conventions:**
**PascalCase** for class names: `UserController`, `TransactionService`**camelCase** for methods and variables: `findUserById`, `isTransactionValid`**ALL_CAPS** for constants: `MAX_RETRY_ATTEMPTS`, `DEFAULT_PAGE_SIZE`Use descriptive names that explain intent**Package Structure:**
```
*.controller - REST controllers
*.service - Business logic
*.repository - Data access
*.dto - Data transfer objects
*.model - Domain entities
shared.config - Configuration classes
```
2. Development Workflow
**Git Commits:**
Always use Angular conventional commits patternUse descriptive commit messages with scopeCreate multiple commits divided by modules, scope, featureExamples: - `feat(transactions): add transaction reconciliation`
- `fix(auth): resolve JWT token expiration issue`
- `docs(api): update OpenAPI transaction endpoints`
**Testing Requirements:**
Write unit tests for all service methodsWrite integration tests for controllersUse `@DataJpaTest` for repository testsMaintain test coverage above 80%Use meaningful test names that describe the scenario**Documentation:**
Keep README.md updated with changesUpdate CHANGELOG.md for all significant changesDocument API endpoints with OpenAPI annotationsAdd JavaDoc for complex business logic3. Security & Best Practices
**Security:**
Never hardcode secrets, use environment variablesValidate all user inputsUse proper authentication and authorizationImplement CORS configurationUse HTTPS in production**Error Handling:**
Use descriptive error messagesImplement proper HTTP status codes (200, 201, 400, 401, 403, 404, 500)Log errors with appropriate levels (ERROR, WARN, INFO, DEBUG)Provide user-friendly error responsesDon't log sensitive information**Performance:**
Use pagination for large datasetsImplement caching where appropriateOptimize database queries with proper indexesUse async processing for long-running tasksUse BigDecimal for all monetary values4. Database & Migrations
**Flyway Migrations:**
Create migrations for all schema changesUse descriptive migration names (e.g., `V1__create_users_table.sql`)Test migrations on development data**Never modify existing migrations**Implement soft deletes where appropriate**Database Best Practices:**
Use proper indexes for performanceFollow naming conventions for tables and columnsUse connection poolingMonitor database performance5. API Design
**RESTful Principles:**
Use proper HTTP methods (GET, POST, PUT, DELETE, PATCH)Implement proper status codesUse consistent response formatsVersion APIs appropriately (`/api/v1/...`)Document all endpoints with OpenAPI**Request/Response:**
Use DTOs for request/response objectsImplement proper validation with `@Valid`Use pagination for list endpointsInclude proper error responses6. Finance Control Specific Rules
**Financial Calculations:**
Always validate financial calculationsUse `BigDecimal` for monetary values (never float or double)Implement proper transaction boundaries with `@Transactional`Handle currency conversions properlyImplement proper audit trails**Brazilian Market Integration:**
Handle API rate limitsImplement proper error handling for external APIsCache market data appropriatelyValidate market data before storing**Transaction Management:**
Implement proper reconciliation logicHandle transaction categories correctlyValidate transaction amountsUse proper transaction isolation levels7. Docker & Deployment
**Docker Best Practices:**
Use multi-stage builds for optimizationUse `.dockerignore` to exclude unnecessary filesUse environment variables for configurationKeep images as small as possible**Environment Configuration:**
Use environment-specific properties filesUse `@ConfigurationProperties` for type-safe configValidate configuration on startupUse Spring profiles for different environments (dev, staging, prod)8. Terminal & Development Tools
**Preferred Commands:**
Use `fd` instead of `find` (install if not available)Use `ripgrep` (rg) instead of `grep`Use `bat` instead of `cat`Use `sudo` when elevated privileges are needed**Development Approach:**
Don't ask for permission to proceed with stepsIf the approach is correct, continue without askingUse scripts for repetitive tasksKeep development environment consistent9. Code Quality & Monitoring
**Quality Tools:**
Use Checkstyle for code styleUse PMD for code analysisUse SpotBugs for bug detectionUse SonarQube for quality gates**Application Monitoring:**
Use Spring Boot Actuator for health checksImplement proper metricsMonitor application performanceSet up alerts for critical issues10. Error Recovery & Resilience
**Application Resilience:**
Implement proper error recoveryUse circuit breakers for external services (e.g., Brazilian market APIs)Implement retry mechanisms with exponential backoffHandle connection failures gracefullyExample Implementation
Controller Example
```java
@RestController
@RequestMapping("/api/v1/transactions")
@RequiredArgsConstructor
public class TransactionController {
private final TransactionService transactionService;
@PostMapping
public ResponseEntity<TransactionResponse> create(
@Valid @RequestBody TransactionRequest request
) {
var response = transactionService.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
}
```
Service Example
```java
@Service
@RequiredArgsConstructor
public class TransactionService {
private final TransactionRepository repository;
@Transactional
public TransactionResponse create(TransactionRequest request) {
// Use BigDecimal for monetary values
BigDecimal amount = request.getAmount();
// Validate and process transaction
var transaction = new Transaction(amount, request.getCategory());
return repository.save(transaction).toResponse();
}
}
```
Key Principles
1. **Never hardcode secrets** - Always use environment variables
2. **Use BigDecimal for money** - Financial accuracy is critical
3. **Test everything** - Maintain >80% coverage
4. **Document your APIs** - OpenAPI for all endpoints
5. **Conventional commits** - Always use Angular pattern with scope
6. **Never modify migrations** - Create new ones instead
7. **Validate inputs** - Use `@Valid` and proper validation
8. **Handle errors gracefully** - Implement proper exception handling
9. **Monitor and log** - Use appropriate log levels and metrics
10. **Optimize performance** - Pagination, caching, async where needed
Important Notes
This is a finance application - **accuracy and security are paramount**All monetary values must use `BigDecimal`Brazilian market integration requires careful rate limiting and error handlingAlways implement proper transaction boundaries for financial operationsKeep test coverage high to ensure financial calculations are correctUse environment-specific configurations for different deployment stages