Java根据Bean实体某一属性获取Bean全部信息

Java根据Bean实体某一属性获取Bean全部信息

业务场景

业务涉及到多个国家,现在需要根据国家的某一属性(以国家简称为例)获得国家的全部信息。

业务代码

package com.example.country;

import lombok.*;

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

@ToString
public class CountryEnvironment {

    @Getter
    private final Integer countryNumber;//国家编码

    @Getter
    private final String countryName;//国家名称

    @Getter
    private final String countryLocation;//国家位置

    @Getter
    private final String countryAbbreviation;//国家简称

    private CountryEnvironment(Integer countryNumber, String countryName, String countryLocation, String countryAbbreviation) {
        this.countryNumber = countryNumber;
        this.countryName = countryName;
        this.countryLocation = countryLocation;
        this.countryAbbreviation = countryAbbreviation;
    }

    private static final Map<String,CountryEnvironment> map = new ConcurrentHashMap<>();

    public static CountryEnvironment getCountryInformation(String countryAbbreviation) {

        if (map.get(countryAbbreviation) == null) {
            CountryEnvironment countryEnvironment;
            switch (countryAbbreviation) {
                case "UK":
                    countryEnvironment = new CountryEnvironment(22, "Britain", "Southern", "UK");
                    break;
                case "FR":
                    countryEnvironment = new CountryEnvironment(33, "France", "Northern", "FR");
                    break;
                default:
                    throw new RuntimeException();
            }
             map.put(countryAbbreviation, countryEnvironment);
        }
        return map.get(countryAbbreviation);
    }

    public static void main(String[] args) {
        //主函数测试
        CountryEnvironment countryEnvironment = getCountryInformation("UK");
        System.out.println(countryEnvironment);
    }
}

测试结果:

在这里插入图片描述

你可能感兴趣的:(Java,java基础知识,java,开发语言,spring)