Microservice architecture learning JSR303 data validation by SpringBoot

“This is the 12th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

About the author

  • The authors introduce

🍓 Blog home Page: author home page 🍓 Introduction: High-quality creator in the JAVA field 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors 🍓, Ali Cloud expert blogger, 51CTO expert blogger, follow me: Pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻


How do you use it first

In Springboot, you can use @ “validated” to verify data. If data is abnormal, an exception will be thrown to facilitate unified processing by the exception center. So let’s make a comment here so that our name can only support Email;

Add the Validation launcher

<! Validation launcher -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Copy the code

2. Add @email

package com.sxau.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Component/ / registered bean
@Validated
@ConfigurationProperties(prefix = "dog")
public class Dog {

// @value (" Value ")
    @email (message = "wrong format ")
    private String lastName;
    @Value("3")
    private Integer age;

}
Copy the code

Result: Default message [not a valid email address];

Data verification can ensure the correctness of data.

Common parameters

@notnull (message=" name cannot be empty ")
private String userName;
@max (value=120,message=" Max ")
private int age;
@email (message=" mailbox format error ")
privateString email; Empty check@NullVerifies that the object isnull
@NotNullVerifies that the object is notnull, the length cannot be checked0The string@NotBlankCheck whether the constraint string is Null and whether the trimmed length is greater than or equal to0, only for strings, and before and after whitespace is removed.@NotEmptyCheck whether the constraint element is NULL or empty. Booelan check@AssertTrueVerify that the Boolean object istrue  
@AssertFalseVerify that the Boolean object isfalseThe length of the check@Size(min=, max=)Verification objects (Array, Collection, Map, String) length is within a given range@Length(min=, max=)string is between min and max included. Date of inspection@PastVerifies that Date and Calendar objects precede the current time@FutureVerifies that Date and Calendar objects are after the current time@PatternVerify that a String complies with regular expression rules....... In addition, we can also customize some data validation rulesCopy the code

Multi-environment switching

Profile is the support of Spring to provide different configuration functions for different environments. You can activate different environment versions to quickly switch environments. (The priority of different positions is shown below)

Multiple profiles

Properties /yml to specify multiple versions of the environment;

Such as:

Application-test. properties represents the test environment configuration

Application-dev.properties represents the development environment configuration

But Springboot does not launch these configuration files directly; it defaults to using the application.properties main configuration file;

We need a configuration to select the environment to activate:

For example, if the dev environment is specified in the configuration file, we can test it by setting a different port number;
If we start SpringBoot, we can see that the configuration has been switched to dev.
spring.profiles.active=dev
Copy the code

Yaml’s multidocument block

As in the Properties configuration file, but using YML to implement it does not require the creation of multiple configuration files, which is much more convenient!

server:
  port: 8081
Select which environment block to activate
spring:
  profiles:
    active: test

---
server:
  port: 8083
spring:
  profiles: dev The name of the configuration environment


---

server:
  port: 8084
spring:
  profiles: test  The name of the configuration environment
Copy the code

Note: If both YML and Properties are configured with ports and no other environment is activated, the properties profile will be used by default!

Configuration file loading location

There are many ways to load configuration files externally, we choose the most common can, in the development of the resource file configuration!

Official external configuration file Description Reference document docs.spring. IO /spring-boot…

Properties or application.yml files in the following locations will be scanned as the default configuration file for Spring Boot:

Priority 1: Config folder configuration file in the project path Priority 2: config folder configuration file in the project path Priority 3: Config folder configuration file in the resource path Priority 4: configuration file in the resource path PriorityCopy the code

The configuration with a higher priority overwrites the configuration with a lower priority.

SpringBoot loads the master configuration file from all four locations; Complementary configuration;

We test the complementarity problem by setting the configuration of a project access path in the lowest configuration file.

Configure the access path for the project
server.servlet.context-path=/ss
Copy the code

Development, operation and maintenance tips

Specify a location to load the configuration file

We can also change the default configuration file location via spring.config.location

Once the project is packaged, we can specify the new location of the configuration file when starting the project using command-line arguments.

In this case, the external configuration file has the highest priority for the same configuration

java -jar spring-boot-config.jar --spring.config.location=F:/application.properties
Copy the code