## Why Use .cursorrules for Java Spring Boot in Cursor AI?
Cursor AI revolutionizes coding by integrating intelligent rules via the `.cursorrules` file, specifically tuned for frameworks like Spring Boot. These rules guide the AI to generate code adhering to Spring's conventions, reducing boilerplate, enforcing best practices, and accelerating development cycles. For Java developers, this means fewer errors, consistent architecture, and faster iterations—from initial project setup to production deployment.
This guide dives deep into a complete set of rules optimized for Java Spring Boot. Each section explores a key rule category, explains its rationale, provides practical examples with code snippets, and offers real-world applications. Implement these in your `.cursorrules` file to transform Cursor into a Spring Boot expert.
## 1. Project Initialization and Structure
Start every Spring Boot project on solid ground. Cursor should default to using [Spring Initializr](https://start.spring.io/) conventions, generating Maven or Gradle builds with the standard layered architecture: controllers, services, repositories, and models.
### Key Directives:
- **Prioritize Maven over Gradle** unless specified, for broader tooling compatibility.
- **Layered Architecture**: Enforce `src/main/java/com/example/demo/` with subpackages for `controller`, `service`, `repository`, `model`, `config`, and `dto`.
- **Include Essential Dependencies**: Always bootstrap with `spring-boot-starter-web`, `spring-boot-starter-data-jpa`, `spring-boot-starter-validation`, `lombok`, `spring-boot-starter-test`, and H2 for dev DB.
**Example .cursorrules Snippet**:
```plaintext
When creating a new Spring Boot project:
- Use Maven
- Group: com.example, Artifact: demo
- Dependencies: web, data-jpa, validation, lombok, test
- Database: H2 for development
```
**Real-World Application**: In a microservices setup, this ensures quick prototyping. For an e-commerce API, Cursor auto-generates a `pom.xml` with exactly these starters, saving 15-30 minutes per project.
## 2. Entity and Model Design
Spring entities demand immutability and validation. Instruct Cursor to use Lombok annotations extensively, JPA standards, and DTOs for API separation.
### Best Practices Deep Dive:
- **Entities**: `@Entity`, `@Table`, `@Id @GeneratedValue`, `@Column`, Lombok's `@Data`, `@NoArgsConstructor`, `@AllArgsConstructor`, `@Builder`.
- **Auditing**: Add `@CreatedDate`, `@LastModifiedDate` with `@EnableJpaAuditing`.
- **DTOs**: Separate from entities using MapStruct or manual mapping to prevent over-posting vulnerabilities.
- **Validation**: `@NotNull`, `@Size`, `@Email`, grouped with `@Valid`.
**Code Example**:
```java
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(min = 3, max = 50)
@Column(unique = true)
private String username;
@Email
private String email;
@CreatedDate
private LocalDateTime createdAt;
}
```
**Pro Tip**: For high-traffic apps like user management systems, this pattern ensures thread-safe, validated models, integrating seamlessly with Spring Security.
## 3. Repository Layer
Leverage Spring Data JPA for CRUD. Cursor must generate `JpaRepository` extensions with custom queries via `@Query` or method naming.
### Implementation Rules:
- Extend `JpaRepository<T, ID>` or `PagingAndSortingRepository` for pagination.
- Use `@Repository` sparingly—Spring Data auto-enables.
- Custom methods: `findByUsernameIgnoreCase`, `@Query(nativeQuery = true)` for complex joins.
- Pagination: `Pageable` in methods.
**Example**:
```java
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsernameIgnoreCase(String username);
Page<User> findByEnabledTrue(Pageable pageable);
@Query("SELECT u FROM User u WHERE u.email = ?1")
List<User> findByEmail(String email);
}
```
**Use Case**: In analytics dashboards, paginated repos handle millions of records efficiently without N+1 issues.
## 4. Service Layer
Services orchestrate business logic: transactional, stateless, and injectable.
### Core Guidelines:
- `@Service`, `@Transactional(readOnly = true)` by default.
- Constructor injection: `@RequiredArgsConstructor`.
- Exception handling: Custom exceptions like `ResourceNotFoundException`.
- Validation: `@Valid` on DTOs.
**Code Snippet**:
```java
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public UserDto getUser(Long id) {
return userRepository.findById(id)
.map(UserMapper::toDto)
.orElseThrow(() -> new ResourceNotFoundException("User not found: " + id));
}
}
```
**Value Add**: Services enable unit testing with `@MockBean`, crucial for CI/CD pipelines.
## 5. Controller and REST API Design
Build RESTful APIs with `@RestController`, HATEOAS optional, and global exception handling.
### Standards:
- `@RestController @RequestMapping("/api/v1")`.
- HTTP methods: `@GetMapping`, `@PostMapping(path = "/", consumes = "application/json")`.
- `@RequestBody @Valid`, `@PathVariable`, `@RequestParam`.
- Responses: `ResponseEntity` with status codes.
- Pagination: `@PageableDefault`.
**Example**:
```java
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("/{id}")
public ResponseEntity<UserDto> getUser(@PathVariable Long id) {
return ResponseEntity.ok(userService.getUser(id));
}
@PostMapping
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
return ResponseEntity.status(HttpStatus.CREATED).body(userService.create(dto));
}
}
```
**Real-World**: Scalable for SaaS platforms, with OpenAPI docs via `springdoc-openapi`.
## 6. Configuration and Security
Secure by default with Spring Security and profiles.
### Rules:
- `application.yml` with profiles: `dev`, `test`, `prod`.
- Security: `@EnableWebSecurity`, JWT or OAuth2.
- CORS: `@CrossOrigin` or global config.
- Actuator: Exposed endpoints secured.
**Config Example**:
```yaml
spring:
profiles:
active: dev
datasource:
url: jdbc:h2:mem:testdb
security:
jwt:
secret: ${JWT_SECRET}
```
## 7. Testing Strategies
Full stack: Unit, Integration, End-to-End.
- `@SpringBootTest`, `@DataJpaTest`, `@WebMvcTest`.
- MockMvc, Testcontainers for realism.
- Coverage: Aim for 80%+.
**Test Snippet**:
```java
@SpringBootTest
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void createUser() throws Exception {
mockMvc.perform(post("/api/v1/users")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(dto)))
.andExpect(status().isCreated());
}
}
```
## 8. Deployment and DevOps
Dockerize with multi-stage builds, Kubernetes manifests.
- `Dockerfile`: OpenJDK 17 slim, layered JAR.
- Profiles for cloud: AWS, GCP.
**Dockerfile Example**:
```dockerfile
FROM eclipse-temurin:17-jdk-alpine as builder
COPY . .
RUN ./mvnw package
FROM eclipse-temurin:17-jre-alpine
COPY --from=builder target/*.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
```
## Implementing These Rules
Copy the full `.cursorrules` into your project root. Cursor reads it on startup, applying rules contextually. Test by prompting: "Create a User CRUD API."
**Benefits**: 2-3x faster development, fewer bugs, idiomatic Spring code. Ideal for teams standardizing practices.
Expand with custom rules for GraphQL, Reactive, or Microservices.
<div style="text-align: center; margin-top: 2rem;">
<a href="https://cursor.directory/java-spring-cursor-rules" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a>
</div>