MockCertMockCert
Menu

Test yourself in exam conditions

A full Spring Certified Professional mock exam: 60 questions in 130 minutes, scored against the real exam's pass mark. Your first one is free.

Start a free mock exam
Domain 3 · 2 topics · about 13 minTopics in this domainTopics

Domain 3 · Overview

Overview

Up next: Web Applications with Spring Boot · 11 steps + check · 6 min

Domain 3 · Topic 1 of 2

Web Applications with Spring Boot

Step 1 of 11

Think first When a GET request reaches a Spring Boot web app, what decides which method runs and how its return value becomes the response?

Why it matters: Questions show a controller or a request and ask which annotation, mapping or return type produces the described response.

Spring Boot sets up a Spring MVC context when Spring MVC is on the classpath. Each request is matched to an annotated controller method. Its return value is then either written to the body by a message converter or resolved as a view.

Step 2 of 11

Term Meaning
@RestController A composed annotation combining @Controller and @ResponseBody, so every method writes to the response body.
HttpMessageConverter The component that turns a return value into the body, for example JSON, and reads request bodies into objects.
HandlerInterceptor A hook around handler execution with preHandle, postHandle and afterCompletion callbacks.
@PathVariable Binds a captured URI template variable to a controller method argument.

Step 3 of 11

Spring MVC on the classpath gives you an MVC application context. The typical main method does nothing except call SpringApplication.run(Class, String...). If Spring MVC and Spring WebFlux are both present, Spring MVC wins. A test of a reactive app then needs spring.main.web-application-type set.

Step 4 of 11

@Controller classes are detected through component scanning. The stereotype registers the class as a bean and marks it as a web component. Annotated controllers need no base class or special interface, and their method signatures are flexible.

Exam trap Since Spring 6.0, a type-level @RequestMapping on an interface alone no longer makes Spring MVC detect a controller when interface proxying is used.

Step 5 of 11

Use @GetMapping instead of a bare @RequestMapping. @RequestMapping can match by URL, HTTP method, parameters, headers and media types. Without a method it matches every HTTP method. @GetMapping also answers HEAD requests with no change to your method.

Exam trap Putting two @RequestMapping annotations on one method does not combine them. Spring logs a warning and uses only the first one.

Step 6 of 11

Each kind of request data has its own binding annotation. URI variables are converted to the argument type automatically. A failed conversion raises TypeMismatchException. A simple value argument that nothing else resolves is treated like @RequestParam.

Where each annotation takes its value from

Annotation Reads Worth knowing
@PathVariable A captured URI template variable Converted to the argument type automatically
@RequestParam Query parameters or form data Required unless required = false or Optional
@RequestBody The request body, via a message converter Not reliable for form data; use @RequestParam

Step 7 of 11

@ResponseBody writes the return value; a plain name selects a view. ResponseEntity behaves like @ResponseBody but also sets the status and headers. Its body is usually a value object rendered as JSON. In a REST controller, a void return can mean no body.

Return choices in a controller method

Return style What reaches the client Status and headers
Method with @ResponseBody Return value serialized by a message converter ResponseEntity adds status and headers
ResponseEntity Body rendered by a registered converter Set by the method
@ResponseBody on the class Every method's return value, written to the body ResponseEntity adds status and headers

Step 8 of 11

Every HandlerMapping supports interceptors around the handler. preHandle runs first; returning false skips the rest of the chain and the handler. postHandle runs after the handler. afterCompletion runs once the whole request has finished.

Exam trap postHandle cannot add a header for @ResponseBody or ResponseEntity methods. The response is already written and committed before it runs.

Step 9 of 11

Add @Valid or @Validated to a @RequestBody argument. Bean Validation then runs on the body. By default, failures raise MethodArgumentNotValidException, which becomes a 400 (BAD_REQUEST) response. An Errors or BindingResult argument lets the controller handle errors itself.

Step 10 of 11

DEFINED_PORT starts an embedded server on a configured port. With this @SpringBootTest web environment, the server listens on the port from application.properties, or on 8080 by default. For fast controller tests without a server, @WebMvcTest auto-configures MockMvc.

Step 11 of 11

  • @RestController equals @Controller plus @ResponseBody, so no view is rendered.
  • Prefer @GetMapping, because a bare @RequestMapping matches every HTTP method.
  • @RequestParam arguments are required unless marked optional.
  • Use ResponseEntity when the method must set the status or headers.
  • Invalid @RequestBody input returns 400 by default.

Sources: Testing Spring Boot Applications :: Spring Boot (opens in a new tab) · Mapping Requests :: Spring Framework (opens in a new tab) · @ResponseBody :: Spring Framework (opens in a new tab) · Return Values :: Spring Framework (opens in a new tab) · Declaration :: Spring Framework (opens in a new tab) · ResponseEntity :: Spring Framework (opens in a new tab) · @RequestBody :: Spring Framework (opens in a new tab) · Interception :: Spring Framework (opens in a new tab)

Check

Check: Web Applications with Spring Boot

Cards to recall, then questions on this topic. About 2 minutes. Nothing is saved without an account.

Loading the cards and questions…

Up next: REST Applications · 10 steps + check · 6 min

Domain 3 · Topic 2 of 2

REST Applications

Step 1 of 10

Think first How should a Spring Boot application build RestTemplate clients and report REST errors to the callers?

Why it matters: Questions describe a REST client or controller need and ask which Spring Boot class, bean or setting fits it.

Spring Boot gives you a RestTemplateBuilder, not a ready RestTemplate, because templates usually need customizing. Controllers can return RFC 9457 problem details for errors. Tests can call those endpoints with or without a running server.

Step 2 of 10

Term Meaning
RestTemplate The classic, imperative Spring class for calling remote REST services; it predates RestClient.
RestTemplateBuilder An auto-configured builder that creates customized RestTemplate instances when you need them.
RestTemplateCustomizer A bean holding an additive customization applied to every template the auto-configured builder builds.
ProblemDetail An RFC 9457 error body; its status property sets the HTTP status of the response.
@WebMvcTest A test annotation, often limited to a single controller, used with @MockitoBean to mock required collaborators.

Step 3 of 10

Pick an imperative or a reactive client to match the app. WebClient suits non-blocking reactive applications on Spring WebFlux. RestTemplate is the classic option and predates RestClient. Teams keep it for existing code they do not want to migrate, or because they know its API.

Spring's REST clients compared

Client Style When to pick it
WebClient Non-blocking, reactive Applications built on Spring WebFlux
RestClient Imperative Imperative code; inject the prototype RestClient.Builder
RestTemplate Imperative, classic Existing code you will not migrate, or a familiar API

Step 4 of 10

Boot auto-configures RestTemplateBuilder, not a RestTemplate bean. Templates usually need customizing before use, so Boot gives you a builder instead. The builder applies sensible HttpMessageConverters and a suitable ClientHttpRequestFactory. Each builder method returns a new instance, so your changes affect only that use.

Example: Builds a RestTemplate with BASIC authentication from the injected builder.

RestTemplate myTemplate = builder
    .basicAuthentication("user", "password")
    .build();
  • basicAuthentication("user", "password"): adds BASIC authentication to the template

Exam trap Autowiring a ready-made RestTemplate fails, because Boot provides no single auto-configured RestTemplate bean. Inject RestTemplateBuilder and build one.

Step 5 of 10

A RestTemplateCustomizer bean applies to all built templates. Every such bean is registered automatically with the auto-configured builder. A RestTemplateBuilder bean of your own replaces the auto-configured one. To pick a specific HTTP client factory instead of the auto-detected one, set spring.http.clients.imperative.factory.

Exam trap Your own RestTemplateBuilder bean does not get customizer beans applied automatically. Configure it with RestTemplateBuilderConfigurer if they should still apply.

Step 6 of 10

Return ProblemDetail to send standard error details. Spring supports RFC 9457, Problem Details for HTTP APIs. Any @ExceptionHandler or @RequestMapping method can return ProblemDetail or ErrorResponse. Its status property sets the HTTP status. For Spring MVC exceptions, extend ResponseEntityExceptionHandler and declare it as an @ControllerAdvice.

Step 7 of 10

Catch RestClientResponseException to decode an error body. With RestTemplate, the client catches RestClientResponseException. Its getResponseBodyAs methods decode the body into a target type, such as ProblemDetail. With WebClient, the matching exception is WebClientResponseException.

Step 8 of 10

RestTestClient can test controllers with or without a server. RestTestClient wraps RestClient and adds a facade for verifying responses. bindToController uses mock requests and responses with no running server. bindToServer runs full end-to-end HTTP tests. Use expectAll(..) to assert every expectation even if one fails.

Exam trap @WebMvcTest does not scan regular @Component and @ConfigurationProperties beans. Provide mock collaborators with @MockitoBean instead.

Step 9 of 10

TestRestTemplate also needs the spring-boot-restclient dependency. It comes from the spring-boot-resttestclient module. Autowire it in a @SpringBootTest with a RANDOM_PORT web environment and @AutoConfigureTestRestTemplate. Adding spring-boot-restclient also enables RestClient.Builder auto-configuration, so put it on the main classpath if main code uses that builder.

Step 10 of 10

  • Spring Boot auto-configures RestTemplateBuilder, not a RestTemplate bean; build templates from it.
  • RestTemplateCustomizer beans apply to every template the auto-configured builder creates.
  • Return ProblemDetail from a controller method to send an RFC 9457 error body.
  • On the client, catch RestClientResponseException to read a RestTemplate error body.

Sources: Calling REST Services :: Spring Boot (opens in a new tab) · Error Responses :: Spring Framework (opens in a new tab) · RestTestClient :: Spring Framework (opens in a new tab) · Testing Spring Boot Applications :: Spring Boot (opens in a new tab)

Check

Check: REST Applications

Cards to recall, then questions on this topic. About 2 minutes. Nothing is saved without an account.

Loading the cards and questions…

Domain 3 · after the last topic

Domain 3 review

Each topic's Check tested it on its own; this mixes them.

Mixed quiz

Take the Domain 3 quiz

6 questions mixed from every topic in this domain, each answer explained. Mixing topics is harder than one at a time, and it is what the exam does. No account needed; with a free account your answers also build your estimated exam score.

Flashcards

Domain 3 flashcards

4 cards with this domain's key facts. Flip each one and check what you knew. No account needed.

Test yourself in exam conditions

A full Spring Certified Professional mock exam: 60 questions in 130 minutes, scored against the real exam's pass mark. Your first one is free.

Start a free mock exam
Next domain · 10% of topicsTesting2 topics

Report a problem

On “”. Tell us what looks wrong; we read every report.

What is the problem?

Optional.