0
0
Spring Bootframework~30 mins

@Size for length constraints in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
@Size for length constraints in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage user profiles. Each user has a username that must be between 3 and 15 characters long.
🎯 Goal: Create a User class with a username field that uses the @Size annotation to enforce the length constraint. Then, configure a controller to accept user data and validate it.
📋 What You'll Learn
Create a User class with a username field
Use @Size(min = 3, max = 15) on the username field
Create a controller method to accept a User object
Enable validation on the controller method parameter
💡 Why This Matters
🌍 Real World
Length constraints on user input fields are common in web applications to ensure data quality and prevent errors.
💼 Career
Understanding how to use validation annotations like @Size is essential for backend developers working with Spring Boot to build robust APIs.
Progress0 / 4 steps
1
Create the User class with a username field
Create a class called User with a private String field named username.
Spring Boot
Need a hint?

Remember to add getter and setter methods for the username field.

2
Add @Size annotation to username field
Add the @Size(min = 3, max = 15) annotation above the username field in the User class. Also, add the import statement for jakarta.validation.constraints.Size.
Spring Boot
Need a hint?

The @Size annotation controls the allowed length of the string.

3
Create a controller method to accept User data
Create a Spring Boot controller class called UserController with a method createUser that accepts a @RequestBody User user parameter. Add @PostMapping("/users") above the method.
Spring Boot
Need a hint?

Use @RestController on the class and @PostMapping on the method.

4
Enable validation on the User parameter
Add the @Valid annotation before the User user parameter in the createUser method. Also, add the import for jakarta.validation.Valid.
Spring Boot
Need a hint?

The @Valid annotation triggers validation of the User object.