AI Generate Spring docs instantly

Spring Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

REST Controllers

3 snippets

HTTP request handling

Basic Controller

@RestController
@RequestMapping("/api/posts")
public class PostController {
    @GetMapping
    public List<Post> list() { return postService.findAll(); }

    @GetMapping("/{id}")
    public Post get(@PathVariable Long id) { return postService.findById(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Post create(@Valid @RequestBody PostDTO dto) {
        return postService.create(dto);
    }
}

ResponseEntity

@GetMapping("/{id}")
public ResponseEntity<Post> get(@PathVariable Long id) {
    return postService.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
}

Query Params

@GetMapping("/search")
public Page<Post> search(
    @RequestParam(defaultValue = "") String q,
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "20") int size
) {
    return postService.search(q, PageRequest.of(page, size));
}

Dependency Injection

3 snippets

Spring IoC container

Constructor Injection

@Service
public class PostService {
    private final PostRepository repo;
    private final EventPublisher events;

    public PostService(PostRepository repo, EventPublisher events) {
        this.repo = repo;
        this.events = events;
    }
}

Stereotypes

@Component     // Generic bean
@Service       // Business logic
@Repository    // Data access
@Controller    // MVC controller
@RestController // @Controller + @ResponseBody
@Configuration // Bean definitions

Bean Definition

@Configuration
public class AppConfig {
    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .registerModule(new JavaTimeModule());
    }
}

JPA & Hibernate

3 snippets

Database persistence

Entity

@Entity
@Table(name = "posts")
public class Post {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private User author;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    private List<Comment> comments;
}

Repository

public interface PostRepository extends JpaRepository<Post, Long> {
    List<Post> findByPublishedTrue();
    Page<Post> findByAuthorId(Long authorId, Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.title LIKE %:q%")
    List<Post> search(@Param("q") String query);
}

Pagination

Pageable pageable = PageRequest.of(0, 20, Sort.by("createdAt").descending());
Page<Post> page = postRepository.findAll(pageable);
page.getContent();    // List<Post>
page.getTotalPages(); // int
page.getTotalElements(); // long

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Security

2 snippets

Authentication and authorization

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .build();
    }
}

Method Security

@PreAuthorize("hasRole('ADMIN')")
public void deletePost(Long id) { ... }

@PreAuthorize("#post.author.id == authentication.principal.id")
public void updatePost(Post post) { ... }

Configuration

4 snippets

Application properties and profiles

Properties

# application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: ${DB_USER}
    password: ${DB_PASS}
  jpa:
    hibernate.ddl-auto: validate
    show-sql: false

@Value

@Value("${app.name:DefaultApp}")
private String appName;

@Value("${server.port}")
private int port;

Config Properties

@ConfigurationProperties(prefix = "app")
public record AppConfig(
    String name,
    int maxRetries,
    Duration timeout
) {}

Profiles

# application-dev.yml
spring.jpa.show-sql: true
# application-prod.yml
spring.jpa.show-sql: false

# Activate: --spring.profiles.active=dev
# Or: SPRING_PROFILES_ACTIVE=prod

Testing

2 snippets

Spring Boot test support

Integration Test

@SpringBootTest
@AutoConfigureMockMvc
class PostControllerTest {
    @Autowired MockMvc mockMvc;

    @Test
    void listPosts() throws Exception {
        mockMvc.perform(get("/api/posts"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(3)));
    }
}

MockBean

@SpringBootTest
class PostServiceTest {
    @MockBean PostRepository repo;
    @Autowired PostService service;

    @Test
    void findById() {
        when(repo.findById(1L)).thenReturn(Optional.of(post));
        assertEquals("Title", service.findById(1L).getTitle());
    }
}

More Cheat Sheets

FAQ

Frequently asked questions

What is a Spring cheat sheet?

A Spring cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Spring. It helps developers quickly look up syntax without searching through documentation.

How do I learn Spring quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Spring concepts?

Key Spring concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Spring code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Spring code using AI.

Related resources

Stop memorizing. Start shipping.

Generate Spring Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week