【WEEK9】 【DAY3】JSR303 Data Validation and Environment Switching 【English Version】

本文详细介绍了如何在SpringBoot项目中使用JSR303进行数据验证,包括添加依赖、修改Java类以应用验证注解、配置多环境YAML文件以及如何在不同环境中切换。同时探讨了配置文件加载策略和使用命令行参数指定配置文件位置。
摘要由CSDN通过智能技术生成

2024.4.24 Wednesday

4. JSR303 Data Validation and Environment Switching

4.1. JSR303 Data Validation (for reference)

4.1.1. Modify Person.java

Add two dependencies (@Validated and @Email)

package com.p8.springboot02config.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component  // Register bean
@ConfigurationProperties(prefix = "person")
@Validated  // Data validation

public class Person {
    // If there is no @Email annotation hint or error, add the hibernate-validator dependency
    @Email()    // Writing message = "Incorrect format" inside the parentheses will change the error message to "Incorrect format"
    private String name;    // Note, you can use shift + f6 to change all names at once
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    ...
}

4.1.2. Modify pom.xml (add dependency)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

4.1.3. Run Springboot02ConfigApplicationTests.java for testing

Insert image description here
Insert image description here

4.1.4. Use Data Validation (Backend) to ensure data correctness

4.1.5. Common Parameters

@NotNull(message="Name cannot be empty")
private String userName;
@Max(value=120, message="Age must not exceed 120")
private int age;
@Email(message="Email format is incorrect")
private String email;

Null checks
@Null       Validates if the object is null
@NotNull    Validates if the object is not null, cannot check strings of length 0
@NotBlank   Checks if the constraint string is not null and its trimmed length is greater than 0, applicable only to strings and trims spaces.
@NotEmpty   Checks if the constrained element is not NULL or EMPTY.

Boolean checks
@AssertTrue     Validates if the Boolean object is true  
@AssertFalse    Validates if the Boolean object is false

Length checks
@Size(min=, max=) Validates that the object (Array, Collection, Map, String) length is within the given range  
@Length(min=, max=) Validates that the string is between min and max included.

Date checks
@Past       Validates that Date and Calendar objects are before the current time  
@Future     Validates that Date and Calendar objects are after the current time  
@Pattern    Validates that the String object adheres to the **regular expression** rules

…etc.
Additionally, we can also define custom data validation rules.
Insert image description here

4.2. Switching Environments

4.2.1. Delete Redundant Files in the Project

As follows:
Insert image description here
Empty the contents of application.yaml and Springboot02ConfigApplicationTests.java
Profiles in Spring provide support for different configurations across various environments, allowing for quick switching between them.

4.2.2. Multiple Configuration Files

When writing the main configuration file, the file name can be application-{profile}.properties/yml, specifying multiple environment versions.

For example

(Create: application.properties, application-test.properties, application-dev.properties)
Insert image description here

application-test.properties represents test environment configuration
server.port=8081
application-dev.properties represents development environment configuration
server.port=8082

However, Spring Boot does not directly launch these configuration files; it defaults to using the application.properties main configuration file
Insert image description here

-> We need to use a setting to select the environment to activate:

# For example, in the configuration file, specify using the dev environment, we can test by setting different port numbers;
# When we start Spring Boot, we can see that it has switched to the dev configuration;
spring.profiles.active=dev

Insert image description here

If dev is changed to test, then run application-test.properties
Insert image description here

4.2.3. Yaml’s Multi-Document Blocks

4.2.3.1. Similar to the properties configuration files, but using Yaml is more convenient as it does not require creating multiple files

Create application.yaml
Insert image description here

server:
  port: 8081  #default
#Select which environment block to activate
spring:
  profiles:
    active: prod

---
server:
  port: 8083
spring:
  profiles: dev #Configuring the environment name


---

server:
  port: 8084
spring:
  profiles: prod  #Configuring the environment name
4.2.3.2. Note: If both yml and properties are configured with a port, and no other environment is activated, the properties configuration file will be used by default! (Delete the .properties file)

Insert image description here

4.2.4. Configuration File Loading Locations

4.2.4.1. There are numerous methods to externally load a configuration file (adding valid paths for application.yaml), and we can choose the most commonly used one, configuring it in the development resources!

https://docs.spring.io/spring-boot/docs/2.7.13/reference/htmlsingle/#features.external-config
Insert image description here
The highest priority is given to the content in the red box in the image below.
Insert image description here
After creating a new folder, you need to change the folder type.
Insert image description here

4.2.4.2. Spring Boot will scan the following locations for application.properties or application.yml files as the default configuration file for Spring Boot:
  • Priority 1: Configuration file in the config folder under the project path (src/main/resources/config/application.yaml)
#src/main/resources/config/application.yaml
server:
  port: 8081

Insert image description here

  • Priority 2: Configuration file under the project path (src/main/resources/application.yaml)
After deleting the previous priority file, this one will run next; the same operations apply (refresh Maven after deleting the configuration file).
#src/main/resources/application.yaml
server:
  port: 8082

Insert image description here

  • Priority 3: Configuration file in the config folder under the resource path (config/application.yaml)
#config/application.yaml
server:
  port: 8083

Insert image description here

  • Priority 4: Configuration file under the resource path (application.yaml)
#application.yaml
server:
  port: 8084

Insert image description here
Here, the application files might not be automatically recognized (indicated by a red yml icon, like:
Insert image description here
), how to change it to a green pea shooter icon?
Change Project Settings -> Modules -> Find the project -> Change to resources type
Insert image description here
Priorities run from high to low, with higher priority configurations overriding lower priority configurations;
Spring Boot will load the main configuration files from all four locations; complementing configurations.

4.2.5. Extension, Operational Tips

Specify location for loading configuration files
We can also change the default configuration file location using spring.config.location
After the project is packaged, we can use command line parameters to specify the new location of the configuration file when launching the project; this scenario is generally handled by operations later on, with external configuration files having the highest priority

java -jar spring-boot-config.jar --spring.config.location=F:/application.properties
  • 36
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值