This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Mountains have peaks, the sea has the other shore, long road, there will be turn, bitter aftertaste, there will be back to gan. Don’t be defeated by the present ordeal, maybe the light is in the moment before you give up. Dream a happy dream with a happy heart. Wake up to a new day.

Introduction to the

This is a utility class that reads yamL configurations based on the SNaKEYAML implementation. The main function is to get data below the specified hierarchy.

I do not know at the beginning why to write this kind, but I know, if I do not send him to me is white write 😂

Main function and use method

demo.yml

ZDC: config: key: value list: - Name: ZDC map age: 12 - name: ZDC map age: 121Copy the code
  1. Supports fetching content after the specified level and returning Map or Obj form

New ConfigBean(" specify file ").prefix("zdc.config").getMap()

New ConfigBean(" specify file ").prefix("zdc.config").getobj ()

  1. Support to get object data after the specified level and format it into the specified class, such as “dzc.config” : new ConfigBean(” specified file “).prefix(” dzc.config “).gett (a.class)

  2. List.1″ : new ConfigBean().prefix(“zdc.config.list.1”).getobj ()

  3. Support to get data after the specified data in list, such as “zdc.config.map.1.name”

    new ConfigBean().prefix("zdc.config.list.1").getString()

Specific code

Maven package required

<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.25</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils-core</artifactId> The < version > 1.8.3 < / version > < / dependency >Copy the code

Java code

package zdc.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

<dependency> * <groupId>org.yaml</groupId> * <artifactId> snakeyAML </artifactId> * <version>1.25</version> * </dependency> * Map ->bean uses this package * <dependency> * <groupId> Commons -beanutils</groupId> * <artifactId> Commons -beanutils-core</artifactId> * <version>1.8.3</version> * </dependency> * * 标 名 *eg: * ZDC: * config: * key: value * list: * - ZDC: * - map: * - name: ZDC map * age: 12 * -name: Map * age: 121 * * Data after a specified level can be obtained, for example, "zdc.config" : New ConfigBean().prefix(" dzc.config ").getobj () * * Support to obtain the specified data in the list, such as "dzc.config.list. 1" : New ConfigBean().prefix(" dzc.config.list.1 ").getobj () * * Support to get the data after the specified data in the list, such as "dzc.config.map.1.name" :new ConfigBean().prefix("zdc.config.list.1").getString() * *@author ZDC
 */
public class ConfigBean {

    /** * Read the resource name */
    private String fileName ="application.yml";
    /** * the obtained object */
    private Object temp;


    /** * create a resource fetch object. By default, get the application.yml file under resources */
    public ConfigBean(a) {
        this.load();
    }

    /** * create a resource fetch object. By default, get fileName under resources *@param fileName
     */
    public ConfigBean(String fileName) {
        this.fileName =fileName;
        this.load();
    }

    /** * loads the specified file */
    private ConfigBean load(a) {
        Yaml yaml = new Yaml();
        InputStream inputStream = this.getClass()
                .getClassLoader()
                .getResourceAsStream(this.fileName);
        this.temp= yaml.load(inputStream);
        return this;
    }



    /**
     * eg "zdc.config.list"
     * eg ""
     * @param prefix
     */
    public ConfigBean prefix(String prefix){

        if(prefix==null || "".equals(prefix.trim())){
            return this;
        }
        // Get the hierarchy
        String[] keys = prefix.trim().split("\ \.");
        for (String key : keys) {
            // Determine the data type
            if(this.temp instanceof Map){
                this.temp= ((Map) this.temp).get(key);
            }
            else if(this.temp instanceof List){
                if (isNumeric(key)) {
                    this.temp= ((List) this.temp).get(Integer.parseInt(key));
                }else{
                    throw new RuntimeException(String.format("Current hierarchy type is List, cannot use [%s] to fetch subset data",key)); }}else{
                throw new RuntimeException("This type is not currently parsed or re-parsed is not supported"); }}return this;
    }

    /** * Returns data of object types, possibly List,Map,Obj *@return* /
    public Object getObj(a){
       return this.temp;
    }

    /** * Returns Map data *@return* /
    public Map getMap(a)  {
     if(this.temp instanceof  Map){
         return (Map)this.temp;
     }
     return null;
    }

    /** * returns data of type List *@return* /
    public List getList(a)  {
        if(this.temp instanceof  List){
            return (List)this.temp;
        }
        return null;
    }

    /** * returns the object type data. If you integrate other libraries, you can call the map2bean method of other libraries directly. This method references commons-beanutils-core@param clazz
     * @param <T>
     * @return* /
    public <T> T getT(Class<T> clazz) throws Exception {
        T obj = clazz.newInstance();
        Map map = this.getMap();
        BeanUtils.populate(obj,map);
        return obj;
    }

    /** * Mandatory String Data *@return* /
    public String getString(a)  {
        return this.temp==null ? "":this.temp.toString();
    }

    /** * returns data of type Integer *@return* /
    public Integer getInteger(a)  {
        String string = getString();
       returnstring! =null? Integer.parseInt(string):null;
    }

//TODO can customize and resolve other types



    /** * Check if it is a number *@param cs
     * @return* /
    public static boolean isNumeric(final CharSequence cs) {
        if (cs == null || cs.length() == 0) {
            return false;
        }
        final int sz = cs.length();
        for (int i = 0; i < sz; i++) {
            if(! Character.isDigit(cs.charAt(i))) {return false; }}return true; }}Copy the code

This series of articles is, by and large, a messy record.

It may have been written down at a previous time when it was needed, when it was needed, when it was useful.

But for much of that time, he was confined to a corner.

Look, he’s all there. He’s not nothing.

Give me a triple when you see this

Source: author: ZOUZDC links: https://juejin.cn/post/7028963866063306760 re the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code