REST Controllers
3 snippetsHTTP 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 snippetsSpring 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 snippetsDatabase 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.
Security
2 snippetsAuthentication 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 snippetsApplication 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 snippetsSpring 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());
}
}