ResourceBundle.getBundle()來讀取自定義的properties配置文件

 

public class CreateHbaseTableDemo {
    public static void main(String[] args) {
        ResourceBundle resourceBundle= ResourceBundle.getBundle("hbase.properties");
        String port = resourceBundle.getString("zookeeperPort");
        String threadMax = resourceBundle.getString("threadMax");
        String keyValueMaxSize = resourceBundle.getString("KeyValueMaxSize");
        System.out.println(port);
        System.out.println(threadMax);
        System.out.println(keyValueMaxSize);
 
 
    }
}

 

springboot方式


import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @Auther: admin
 * @Date: 2020/6/3 20:16
 * @Description: 讀取自定義配置文件 properties配置文件
 */
public class ResourceUtils {

    public static final String CONTEX = "test";

    private static ResourceBundle resourceBundle = null;
    private static Map cache = new HashMap(16);


    static {
        resourceBundle = ResourceBundle.getBundle(CONTEX);
    }

    private ResourceUtils() {
    }

    public static ResourceBundle getResourceBundle() {
        return resourceBundle;

    }

    public static String getResourceValue(String key) {
        try {
            Object obj = null;
            if (cache.containsKey(key)) {
                obj = cache.get(key);
                if (!(obj instanceof String)) {
                    return "";
                }
                return (String) obj;
            }
            obj = resourceBundle.getString(key);
            cache.put(key, obj);

            return (String) obj;
        } catch (Exception e) {
            return "";
        }

    }
}

 

import com.htf.utils.ResourceUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Auther: admin
 * @Date: 2020/6/3 20:42
 * @Description:
 */
@Configuration
public class ResourceConfig {
    
    @Bean
    public static void initResourceBundle() {
        String age = ResourceUtils.getResourceValue("test.age");
        String name = ResourceUtils.getResourceValue("test.name");
        System.out.println(age);
        System.out.println(name);
    }
}

 

自定義properties配置文件

test.name=aaa
test.age=ssss

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章