'How can I Set method annotations using code(or xml) in spring boot

public class SizeDto {
    @Size(max = 5, min = 3)
    private String size;
}

(In this case, I want to specify "@Size(max = 5, min = 3)" annotations using code(or xml) not "@" annotations.

I want to set @validate annotations using code(or xml).

How can I specify annotations (@Size, @Email, @CustomValidation) with codes or xml?

I don't want to solve the problem by using "AbstractProcessor" that creates a new code itself.

I just want to do it like registering a bean using xml or @Config annotations.



Solution 1:[1]

First Add these dependency into your pom.xml file.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
and if it is not able to import javax.validation.valid api.
Add the following dependency to your pom.xml
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

#######################################################
Now Make your java Object as follows

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class SizeDto {
    @NotEmpty
    @Size(min = 10, max = 25,message ="email size/length should be between 10 to 25")
    @Email(message = "email is not valid",regexp="(?:[a-z0-9!#$%&'*+/=? 
    ^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01- 
    \x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01- 
    \x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+ 
    [a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0- 
    9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a- 
    z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01- 
    \x09\x0b\x0c\x0e-\x7f])+)\])")
    private String email;
}

You can add more field to your java object and to add validation on those fields you have add different validation annotations as per your requirement.

And to enabled validation on this java object in your cotroller whereever you have written your api add @Valid annotation along with @RequestBody annotation like:

@Override
@PostMapping(value ="/email")
public ResponseEntity<?> fetchEmailData(@Valid @RequestBody SizeDto size) 
{
    return null;
}

//this will enable the spring that take sizeDto as input but @Valid 
notation will says validate sizeDto according to validation constraint 
that we have applied to  sizeDto object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KM PRIYA AGRAWAL