java-springboot
Scannednpx machina-cli add skill github/awesome-copilot/java-springboot --openclawSpring Boot Best Practices
Your goal is to help me write high-quality Spring Boot applications by following established best practices.
Project Setup & Structure
- Build Tool: Use Maven (
pom.xml) or Gradle (build.gradle) for dependency management. - Starters: Use Spring Boot starters (e.g.,
spring-boot-starter-web,spring-boot-starter-data-jpa) to simplify dependency management. - Package Structure: Organize code by feature/domain (e.g.,
com.example.app.order,com.example.app.user) rather than by layer (e.g.,com.example.app.controller,com.example.app.service).
Dependency Injection & Components
- Constructor Injection: Always use constructor-based injection for required dependencies. This makes components easier to test and dependencies explicit.
- Immutability: Declare dependency fields as
private final. - Component Stereotypes: Use
@Component,@Service,@Repository, and@Controller/@RestControllerannotations appropriately to define beans.
Configuration
- Externalized Configuration: Use
application.yml(orapplication.properties) for configuration. YAML is often preferred for its readability and hierarchical structure. - Type-Safe Properties: Use
@ConfigurationPropertiesto bind configuration to strongly-typed Java objects. - Profiles: Use Spring Profiles (
application-dev.yml,application-prod.yml) to manage environment-specific configurations. - Secrets Management: Do not hardcode secrets. Use environment variables, or a dedicated secret management tool like HashiCorp Vault or AWS Secrets Manager.
Web Layer (Controllers)
- RESTful APIs: Design clear and consistent RESTful endpoints.
- DTOs (Data Transfer Objects): Use DTOs to expose and consume data in the API layer. Do not expose JPA entities directly to the client.
- Validation: Use Java Bean Validation (JSR 380) with annotations (
@Valid,@NotNull,@Size) on DTOs to validate request payloads. - Error Handling: Implement a global exception handler using
@ControllerAdviceand@ExceptionHandlerto provide consistent error responses.
Service Layer
- Business Logic: Encapsulate all business logic within
@Serviceclasses. - Statelessness: Services should be stateless.
- Transaction Management: Use
@Transactionalon service methods to manage database transactions declaratively. Apply it at the most granular level necessary.
Data Layer (Repositories)
- Spring Data JPA: Use Spring Data JPA repositories by extending
JpaRepositoryorCrudRepositoryfor standard database operations. - Custom Queries: For complex queries, use
@Queryor the JPA Criteria API. - Projections: Use DTO projections to fetch only the necessary data from the database.
Logging
- SLF4J: Use the SLF4J API for logging.
- Logger Declaration:
private static final Logger logger = LoggerFactory.getLogger(MyClass.class); - Parameterized Logging: Use parameterized messages (
logger.info("Processing user {}...", userId);) instead of string concatenation to improve performance.
Testing
- Unit Tests: Write unit tests for services and components using JUnit 5 and a mocking framework like Mockito.
- Integration Tests: Use
@SpringBootTestfor integration tests that load the Spring application context. - Test Slices: Use test slice annotations like
@WebMvcTest(for controllers) or@DataJpaTest(for repositories) to test specific parts of the application in isolation. - Testcontainers: Consider using Testcontainers for reliable integration tests with real databases, message brokers, etc.
Security
- Spring Security: Use Spring Security for authentication and authorization.
- Password Encoding: Always encode passwords using a strong hashing algorithm like BCrypt.
- Input Sanitization: Prevent SQL injection by using Spring Data JPA or parameterized queries. Prevent Cross-Site Scripting (XSS) by properly encoding output.
Source
git clone https://github.com/github/awesome-copilot/blob/main/plugins/java-development/skills/java-springboot/SKILL.mdView on GitHub Overview
A practical guide to building high-quality Spring Boot applications by following proven patterns across project setup, dependency injection, configuration, web layer, service and data layers, testing, logging, and security.
How This Skill Works
The guidance is organized into concrete, repeatable patterns: adopt Maven or Gradle for dependency management, use Spring Boot starters, implement constructor-based injection with private final fields, externalize configuration with application.yml/properties and bind with @ConfigurationProperties, and structure code by feature. It also covers REST DTO usage with validation, global error handling, transactional service methods, and leveraging Spring Data JPA for data access.
When to Use It
- Starting a new Spring Boot project and choosing a build tool (Maven/Gradle) and starters.
- Designing REST APIs where DTOs, validation, and consistent error handling matter.
- Externalizing configuration across environments using application.yml/properties and profiles.
- Implementing business logic in @Service classes with appropriate @Transactional boundaries.
- Setting up testing with unit tests, integration tests, and test slices (e.g., @WebMvcTest, @DataJpaTest) and optional Testcontainers.
Quick Start
- Step 1: Create a Spring Boot project with a build tool (Maven/Gradle) and include starters like spring-boot-starter-web and spring-boot-starter-data-jpa.
- Step 2: Refactor packages to be feature/domain-based and switch to constructor-based dependency injection with private final fields.
- Step 3: Externalize config to application.yml, create @ConfigurationProperties classes, and define dev/prod profiles; ensure secrets come from environment variables.
Best Practices
- Use constructor-based dependency injection and declare dependencies as private final.
- Organize code by feature/domain (e.g., com.example.app.order) rather than by layer.
- Externalize configuration with application.yml/properties and bind to type-safe POJOs via @ConfigurationProperties.
- Expose APIs with DTOs, validate requests with Bean Validation (JSR 380), and implement a global error handler with @ControllerAdvice.
- Keep services stateless and manage transactions declaratively with @Transactional at the most granular level necessary.
Example Use Cases
- A web application using spring-boot-starter-web and spring-boot-starter-data-jpa with a feature-based package layout.
- Controllers returning DTOs with @Valid-annotated request bodies and a global @ControllerAdvice for consistent errors.
- Configuration bound to @ConfigurationProperties classes, with multiple profiles (dev/prod) and secrets sourced from environment variables.
- Service classes annotated with @Service, containing business logic and @Transactional boundaries for database operations.
- Repositories extending JpaRepository with custom @Query methods or JPA Criteria API, plus DTO projections for optimized queries.