SpringBoot enumeration into the actual combat

foreword

The front-end uses enumeration names for parameter passing, which is more semantic than the traditional use of code[1,2,3,4,5]


1. What is an enumeration?

  • An enum is a special class that represents a finite set of values. In Java, enum types are a way to define named constants. Enum constants are static, final, and public, available throughout the application, and have their own name and value.
  • It is a way of grouping constants into a group. Enums can be used as constant pools, which can improve code readability and maintainability. Enums are very useful in Java as they reduce hard coding in the code and make the code more natural and understandable

Second, the advantages of enumeration

  • Safety: Enum constants are static and immutable, determined at compile time, which means they are type-safe.
  • Ease of maintenance: Using an enumeration allows related constants to be grouped together, so it is easy to maintain.
  • Ease of reading: Since the enumeration constants have their own names, the code is easier to understand and read.
  • Ease of writing: Using enums reduces hardcoding in your code, as they provide a more natural way to define constants.

3. Disadvantages of enumeration

  • Constraints: Once an enum defines a constant set, it cannot be easily changed. This may cause some inconvenience.
  • Complexity: In some cases, enums can be overly complex or undesirable. For example, if only a single constant needs to be used in the code, then defining a whole enumeration may increase the complexity of the code.

4. Use steps

1. Code implementation

1.1. Enumeration

  • The @JsonFormat(shape = JsonFormat.Shape.OBJECT) annotation is an annotation used to control the shape during JSON serialization and deserialization
  • The @JsonFormat(shape = JsonFormat.Shape.OBJECT) annotation can be used to output a Java object as a single object instead of multiple properties. That is to say, the @JsonFormat annotation treats the Java object as a whole and outputs it as a JSON object.
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;


/**
 * @author 性别
 */

@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Gender {
    
    
    /**
     * 男士
     */
    MALE(1, "男士"),

    /**
     * 女士
     */
    FEMALE(2, "女士");

    /**
     * 编码
     */

    private final Integer code;
    /**
     * 注释
     */
    //@JsonValue
    private final String desc;

    Gender(Integer code, String desc) {
    
    
        this.code = code;
        this.desc = desc;
    }

    public static Gender fromString(String value) {
    
    
        if (value == null) {
    
    
            return null;
        }
        for (Gender gender : Gender.values()) {
    
    
            if (gender.name().equalsIgnoreCase(value)) {
    
    
                return gender;
            }
        }
        return null;
    }

    public static Gender fromCode(Integer code) {
    
    
        if (code == null) {
    
    
            return null;
        }
        for (Gender gender : Gender.values()) {
    
    
            if (gender.getCode().equals(code)) {
    
    
                return gender;
            }
        }
        throw new IllegalArgumentException("Invalid code: " + code);
    }
}

1.2. Entities

  • The @ModelAttribute("gender") annotation is the annotation used in Spring MVC to add data to the model. It is usually used to load some basic data before processing the request, thus lightening the load between the view and the controller
  • The @ModelAttribute("gender") annotation adds an attribute named "gender" to the model and sets its value as the return value of the tagged method. Also, if the value attribute is used, the value will be used as the property's name instead of the default name. When the view is rendered, this property will be passed to the view so that it can be used in the view
import com.mxf.code.enums.Gender;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * @author mxf
 * @version 1.0
 * @description: Person
 * @date 2023/5/25
 */

public class Person {
    
    
    private Long id;
    private String name;
    private Gender gender;

    public Long getId() {
    
    
        return id;
    }

    public void setId(Long id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Gender getGender() {
    
    
        return gender;
    }

    @ModelAttribute("gender")
    public void setGender(Gender gender) {
    
    
        this.gender = gender;
    }
}

1.3. Control layer

import com.mxf.code.entity.Person;
import com.mxf.code.enums.Gender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author mxf
 * @version 1.0
 * @description: 枚举Controller
 * @date 2023/5/25
 */
@RestController
@RequestMapping("enum/test")
@Slf4j
public class EnumController {
    
    

    @GetMapping("getTest01")
    @ResponseBody
    public Gender getTest01(@ModelAttribute("gender") Gender gender) {
    
    
        return gender;
    }

    @GetMapping("getTest02")
    public Person getTest02(Person person) {
    
    
        return person;
    }

    @PostMapping("postTest01")
    @ResponseBody
    public Gender postTest01(@ModelAttribute("gender") Gender gender) {
    
    
        return gender;
    }

    @PostMapping("postTest02")
    public Person postTest02(@RequestBody Person person) {
    
    
        return person;
    }

    @PutMapping("putTest01")
    public Gender putTest01(@ModelAttribute("gender") Gender gender) {
    
    
        return gender;
    }

    @PutMapping("putTest02")
    public Gender putTest02(@RequestBody Person person) {
    
    
        return person.getGender();
    }

    @PutMapping("putTest03")
    public Person putTest03(@RequestBody Person person) {
    
    
        return person;
    }
}

2. Postman test

2.1. Get request

2.1.1. Enumeration parameters

@GetMapping("getTest01")
@ResponseBody
public Gender getTest01(@ModelAttribute("gender") Gender gender) {
    
    
    return gender;
}

insert image description here

2.1.2. Object enumeration attribute parameters

@GetMapping("getTest02")
public Person getTest02(Person person) {
    
    
    return person;
}

insert image description here


2.2. Post request

2.2.1. Enumeration parameters

@PostMapping("postTest01")
@ResponseBody
public Gender postTest01(@ModelAttribute("gender") Gender gender) {
    
    
    return gender;
}

insert image description here

2.2.2. Object enumeration attribute parameters

@PostMapping("postTest02")
public Person postTest02(@RequestBody Person person) {
    
    
    return person;
}

insert image description here


2.3.Put request

2.3.1. Enumeration parameters

@PutMapping("putTest01")
public Gender putTest01(@ModelAttribute("gender") Gender gender) {
    
    
    return gender;
}

insert image description here

2.3.2. Object enumeration attribute parameters

@PutMapping("putTest02")
public Gender putTest02(@RequestBody Person person) {
    
    
    return person.getGender();
}

insert image description here


Summarize

Using the enumeration name to pass parameters can more intuitively display the specific meaning of its parameters, such as passing MALE or 1 as a parameter

Guess you like

Origin blog.csdn.net/weixin_44063083/article/details/130872595
Recommended