当前位置:网站首页>Enumeration gets values based on parameters

Enumeration gets values based on parameters

2022-07-06 20:04:00 Mr_ ZhangAdd

The problem background

Fixed business types are often encountered in business , In the database, its meaning is often identified in numerical order 0- Woman 1- male

Main idea :

Define enumeration 》 Get the value composition in the enumeration map Generate bean》 Get... By context bean Get the corresponding value

enumeration

import lombok.Getter;
import lombok.Setter;

/**
 * @author Xuewei.Zhang
 * @date 2022/7/5
 */
public enum FlowEnum {

    ORDER(0, " Order "),
    PROCUREMENT(1, " purchase "),
    PRODUCTION(2, " production "),
    REIMBURSE(3, " Reimbursement "),
    VACATE(4, " Ask for leave "),
    ;

    @Getter
    @Setter
    private Integer code;

    @Getter
    @Setter
    private String msg;

    FlowEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

}

assemble bean

import com.zxw.common.core.base.enums.FlowEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Xuewei.Zhang
 * @date 2022/7/5
 */
@Configuration
public class FlowBean {

    @Bean("FlowEnumBean")
    public Map<String, Integer> FlowEnumBean() {
        Map<String, Integer> map = new ConcurrentHashMap<>();
        for (FlowEnum flowEnum : FlowEnum.values()) {
            map.put(flowEnum.getMsg(), flowEnum.getCode());
        }
        return map;
    }
}

Get the corresponding value


import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Xuewei.Zhang
 * @date 2022/7/5
 */
@Configuration
public class BeanUtils {

    private static ApplicationContext applicationContext;

    @Resource
    public void setApplicationContext(ApplicationContext applicationContext) {
        BeanUtils.applicationContext = applicationContext;
    }

    public  static Integer getCodeByServiceName(String serviceName) {
        Map<String, Integer> map = (Map<String, Integer>) applicationContext.getBean("FlowEnumBean");
        return map.get(serviceName);
    }

}

Use


    @Override
    @InitInsertInfo
    public FlowTypeVO add(FlowTypeVO flowTypeVO) {
     // Use         
flowTypeVO.setServiceType(BeanUtils.getCodeByServiceName(flowTypeVO.getServiceTypeName()));
        flowTypeMapper.insert(flowTypeVO);
        return flowTypeVO;
    }

test result :

 

原网站

版权声明
本文为[Mr_ ZhangAdd]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061209065085.html